Skip to content

Fast API

FastAPI targets development of web APIs. FastAPI was mainly designed to build APIs, and its default input is JSON. FastAPI itself does not include a web server but recommends Uvicorn.

$ pip install fastapi uvicorn

You can start Uvicorn and the FastAPI web application in two ways:

  1. externally (or)
  2. internally

1. To start Uvicorn externally, via the command line

# Start Uvicorn with the command line
$ uvicorn hello:app --reload

# The hello refers to the hello.py file, and app is the FastAPI variable name within it.

2. To start Uvicorn internally in the application itself

# Start Uvicorn internally

from fastapi import FastAPI

app = FastAPI()

@app.get("/hi")
def greet():
  return "Hello? World?"

if __name__ == "__main__":
  import uvicorn
  uvicorn.run("hello:app", reload=True)

In either case, that reload tells Uvicorn to restart the web server if hello.py changes.

Test FastAPI after Installing

To make sure the installation worked, we can open a Python interactive shell and try to import the FastAPI package:

$ python

>>> from fastapi import FastAPI

Installing the HTTPie command-line utility

  • FastAPI automatic documentation (we'll talk about this later in the book)
  • Postman, a GUI tool to perform HTTP requests
  • cURL, the well-known and widely used command-line tool to perform network requests
  • HTTPie, a command-line tool aimed at making HTTP requests with an intuitive syntax, JSON support, and syntax highlighting.
# GET
$ http GET https://603cca51f4333a0017b68509.mockapi.io/todos

#POST
$ http -v POST https://603cca51f4333a0017b68509.mockapi.io/todos text="My new task"

#
$ http -v GET https://603cca51f4333a0017b68509.mockapi.io/todos "My-Header: My-Header-Value"

Web Tools

The main Python web tools (FastAPI):

  • FastAPI: The web framework itself
  • Uvicorn: An asynchronous web server
  • HTTPie: A text web client, similar to curl
  • Requests: A synchronous web client package
  • HTTPX: A synchronous/asynchronous web client package

SQLAlchemy

SQLAlchemy is the most popular ORM library and can establish communication between any Python-based application and database platform.

This ORM is a boilerplated interface that aims to create a database-agnostic data layer that can connect to any database engine. But compared to other ORMs, SQLAlchemy is DBA-friendly because it can generate optimized native SQL statements.

pip install SQLAlchemy

Installing the database driver

SQLAlchemy will not work without the required database driver. It is mandatory to install the psycopg2 dialect since the database of choice is PostgreSQL:

pip install psycopg2

Reference