Python FastAPI Overview

FastAPI is a modern, fast (high-performance) web framework for building APIs with Python 3.6+ based on standard Python type hints. It is built on top of the asynchronous framework Starlette and uses Pydantic for data validation and serialization. FastAPI is known for its simplicity, speed, and automatic generation of OpenAPI and JSON Schema documentation. In this tutorial, we’ll introduce the core features of FastAPI and how to create a simple API.

1. Introduction to FastAPI

FastAPI is designed to make it easier and faster to build APIs with Python. It’s built on top of modern web standards such as HTTP/2, async programming, and OpenAPI, which makes it an excellent choice for building highly performant APIs with minimal boilerplate code. FastAPI also offers automatic validation of request and response data using Pydantic models, making it easy to handle and document your API’s inputs and outputs.

2. Installing FastAPI

To get started with FastAPI, you need to install it along with the ASGI server Uvicorn, which will run your FastAPI application. You can install both using pip:

pip install fastapi uvicorn

Try It Now

3. Creating a Simple FastAPI Application

Once FastAPI and Uvicorn are installed, you can create your first FastAPI application. Create a Python file (e.g., main.py) and start writing the code.

from fastapi import FastAPI

# Create the FastAPI app instance
app = FastAPI()

# Define a route for the root endpoint
@app.get("/")
def read_root():
    return {"message": "Hello, FastAPI!"}

Try It Now

This example defines a route for the root URL (/) that returns a simple JSON message. To run the FastAPI app, use the following command:

uvicorn main:app --reload

Try It Now

Your FastAPI app will now be running at http://127.0.0.1:8000/.

4. Path Parameters

FastAPI allows you to create dynamic routes by using path parameters. You can include variables in the URL by wrapping them in curly braces. Here’s an example of a route that takes a path parameter:

@app.get("/greet/{name}")
def greet(name: str):
    return {"message": f"Hello, {name}!"}

Try It Now

Now, visiting http://127.0.0.1:8000/greet/John will return the message {"message": "Hello, John!"}.

5. Query Parameters

In addition to path parameters, FastAPI supports query parameters. These are values passed in the URL after the ? character. Here’s an example:

@app.get("/items/")
def read_item(skip: int = 0, limit: int = 10):
    return {"skip": skip, "limit": limit}

Try It Now

With this route, you can access the URL like http://127.0.0.1:8000/items/?skip=5&limit=20 to retrieve the values for skip and limit.

6. Request Body and Data Validation

FastAPI allows you to handle complex request bodies using Pydantic models. Pydantic models help validate and parse the incoming data. Here’s an example of how to handle a POST request with a JSON body:

from pydantic import BaseModel

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

@app.post("/items/")
def create_item(item: Item):
    return {"name": item.name, "price": item.price}

Try It Now

In the above example, the Item Pydantic model defines the structure of the request body. FastAPI will automatically validate the incoming request and ensure that the data matches the defined model.

7. Response Models

FastAPI also supports response models, which allow you to specify the structure of the data that will be returned by the API. You can define a response model just like a request model using Pydantic:

from typing import List

class ItemResponse(BaseModel):
    name: str
    description: str = None
    price: float

@app.get("/items/", response_model=List[ItemResponse])
def get_items():
    return [
        {"name": "Item 1", "price": 20.0},
        {"name": "Item 2", "price": 30.0}
    ]

Try It Now

By specifying the response_model, FastAPI will automatically format the response to match the defined model.

8. Automatic API Documentation

One of the great features of FastAPI is its automatic generation of interactive API documentation. Once your FastAPI application is running, you can view the interactive documentation at:

FastAPI uses the OpenAPI standard to generate this documentation automatically based on the routes, parameters, and data models in your application. It’s an excellent tool for testing and exploring your API.

Conclusion

In this tutorial, you learned the basics of FastAPI, including how to create routes, handle path and query parameters, validate request data using Pydantic models, and generate automatic API documentation. FastAPI is a powerful and fast web framework for building APIs, and its simplicity and performance make it an excellent choice for modern web applications.