2022-07-04

FastAPI

What is FastAPI

FastAPI is a cutting-edge, high-performance web framework used for constructing APIs (Application Programming Interfaces) with Python 3.6 and above. It is built on top of Starlette for web routing and Pydantic for data validation and settings management. These dependencies ensure FastAPI's speed and reliability, making it an excellent choice for modern web development.

FastAPI was first released to the public in December 2018. Since then, it has gained significant popularity due to its speed, ease of use, and comprehensive feature set.

FastAPI's Core Features

One of FastAPI's most notable features is its speed. When compared to other popular Python frameworks, FastAPI stands out both in terms of performance and quickness in development. It is one of the fastest Python frameworks available, only marginally slower than NodeJS and Go.

FastAPI is designed around Python's type hints feature. Type hints are a feature in Python that allow developers to indicate the expected type of a function's arguments or return value. FastAPI uses these type hints to handle data validation, serialization, and documentation, leading to fewer bugs and cleaner code.

FastAPI is also known for its automatic, interactive API documentation. When you create a new API endpoint in FastAPI, the framework automatically generates an interactive documentation page for that endpoint using Swagger UI or ReDoc. This feature allows developers and users to interact with the API, understand its functionality, and even test different parameters and see the responses, all from their web browsers.

Another notable feature of FastAPI is its robust support for asynchronous request handling. Built on top of Starlette, an asynchronous web framework, FastAPI supports Python's native async and await keywords, allowing developers to write asynchronous code for handling IO-bound operations efficiently.

FastAPI also provides support for OAuth2 authentication, JSON Web Tokens, query parameters, request bodies, path parameters, cookies, headers, and other HTTP features, making it a comprehensive tool for building robust and secure web APIs.

Installation

FastAPI is available as a package on the Python Package Index (PyPI), and you can install it using pip.

bash
$ pip install fastapi

FastAPI needs an ASGI (Web Server Gateway Interface) server to run. Uvicorn is one of the ASGI servers that you can use. It's a lightning-fast ASGI server implementation, using uvloop and httptools.

bash
$ pip install uvicorn

Creating FastAPI Application

Defining Routes

In FastAPI, a route is a way to define an endpoint in your application. An endpoint is a specific URL where your API can be accessed. In FastAPI, you define routes using Python functions, also known as "path operations".

Let's create a simple FastAPI application with a single route. Open your preferred code editor, create a new Python file named main.py, and write the following code:

main.py
from fastapi import FastAPI

app = FastAPI()

@app.get("/")
def read_root():
    return {"Hello": "World"}

In the above code, we first import the FastAPI class. We then create an instance of this class and assign it to the variable app. This instance will be the main point of interaction with our API.

We then define a route with the @app.get("/") decorator. This decorator tells FastAPI that the function below should be called whenever a GET request is made to the root ("/") URL. The function read_root() simply returns a JSON response with the text "Hello, World".

Running Application

With your first route defined, you can now run your FastAPI application. To do this, open your terminal or command prompt, navigate to the directory containing your main.py file, and type:

bash
$ uvicorn main:app --reload

Here, main:app tells Uvicorn to look for an application instance in the main.py file named app. The --reload flag enables hot reloading, meaning the server will automatically update whenever you make changes to your code.

Once Uvicorn is running, you can open your web browser and navigate to http://localhost:8000/. You should see the JSON response from your read_root function: {"Hello": "World"}.

FastAPI's Data Handling

In this chapter, I will take a closer look at how FastAPI handles data in the form of the request body, query parameters, and path parameters.

Request Body

In FastAPI, you can read the request body of HTTP methods (like POST and PUT) using Pydantic models. Pydantic models allow you to define the data structure and automatically handle validation, serialization, and documentation.

Let's take a look at an example. First, define a Pydantic model:

python
from pydantic import BaseModel

class Item(BaseModel):
    name: str
    description: str = None
    price: float
    quantity: int

Here, name, price, and quantity are required fields, while description is optional.

Next, use this model in a route:

python
@app.post("/items/")
def create_item(item: Item):
    return item

In this route, FastAPI will expect a JSON object in the request body that matches the structure of the Item model. It will automatically validate the data, serialize it into a Pydantic model, and include it in your route function.

A client can send a POST request to this route with a JSON object in the request body. Here's an example using the curl command:

bash
$ curl -X POST "http://localhost:8000/items/" -H "accept: application/json" -H "Content-Type: application/json" -d "{\"name\":\"Foo\",\"price\":50.5,\"quantity\":10}"

Query Parameters

Query parameters are the part of a URL that come after a question mark (?) and are typically used to sort/filter the content. FastAPI makes handling query parameters very straightforward.

Let's add a route that accepts query parameters:

python
@app.get("/items/")
def read_items(skip: int = 0, limit: int = 10):
    return items[skip : skip + limit]

In this example, skip and limit are optional query parameters with default values of 0 and 10, respectively.

A client can send a GET request to this route with query parameters in the URL. Here's an example using the curl command:

bash
$ curl -X GET "http://localhost:8000/items/?skip=20&limit=10" -H "accept: application/json"

Path Parameters

Path parameters, also known as path variables, are variables that are part of the URL path. They can be defined as function arguments.

Here's how to use a path parameter in FastAPI:

python
@app.get("/items/{item_id}")
def read_item(item_id: int):
    return {"item_id": item_id}

In this route, item_id is a path parameter that FastAPI will extract from the URL and pass to your route function as an argument.

A client can send a GET request to this route with the item ID in the URL path. Here's an example using the curl command:

bash
$ curl -X GET "http://localhost:8000/items/5" -H "accept: application/json"

References

https://fastapi.tiangolo.com/

Ryusei Kakujo

researchgatelinkedingithub

Focusing on data science for mobility

Bench Press 100kg!