2 min read

Python FastAPI Framework

FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.6+ based on standard Python type hints.

Installation

You need to install fastapi and an ASGI server, such as uvicorn.

pip install fastapi
pip install "uvicorn[standard]"

Basic Application

Create a file main.py:

from fastapi import FastAPI

app = FastAPI()

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

Running the Server

Run the server with:

uvicorn main:app --reload
  • main: the file main.py (the Python "module").
  • app: the object created inside of main.py with the line app = FastAPI().
  • --reload: make the server restart after code changes.

Path Parameters

You can declare path "variables" or "parameters" with the same syntax used by Python format strings.

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

FastAPI uses type hints (item_id: int) to validate the data. If you visit /items/foo, you will get an HTTP error because "foo" is not an integer.

Query Parameters

When you declare other function parameters that are not part of the path parameters, they are automatically interpreted as "query" parameters.

@app.get("/items/")
def read_item(skip: int = 0, limit: int = 10):
    return {"fake_items_db": [{"item_name": "Foo"}, {"item_name": "Bar"}][skip : skip + limit]}

URL example: http://127.0.0.1:8000/items/?skip=0&limit=10

Request Body

To send data to your API, you use Pydantic models.

from typing import Optional
from fastapi import FastAPI
from pydantic import BaseModel

class Item(BaseModel):
    name: str
    price: float
    is_offer: Optional[bool] = None

app = FastAPI()

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

Automatic Documentation

FastAPI automatically generates interactive API documentation.

  • Swagger UI: Go to http://127.0.0.1:8000/docs.
  • ReDoc: Go to http://127.0.0.1:8000/redoc.

programming/python/python