Learning

FastAPI

| 2 min read

Installation

pip install fastapi
pip install uvicorn

Defining an endpoint path

from fastapi import FastAPI

app = FastAPI()

@app.get("/") # endpoint route definition.
def root():
	return {"Hello": "World" }

Running the uvicorn server

uvicorn main:app --reload

Adding more routes

items = []

@app.post(("/items"))
def create_item(item: str):
	items.append(item)
	return items
# POST /items?item=orange

@app.get("/items/{item_id}")
def get_item(item_id: int) -> str:
	item = items[item_id]
	return item

Raising errors

from fastapi import FastAPI, HTTPException

app = FastAPI()

items = []

@app.get("/items/{item_id}")
def get_item(item_id: int) -> str:
	if item_id < len(items):
		return items[item_id]
	else:
		raise HTTPException(status_code=404, detail=f"Item {item_id} not found")

Request and Path Parameters

@app.get("/items")
def list_items(limit: int = 10):
	return items[0:limit]
# GET /items?limit=3

Data Structures with Pydantic

from fastapi import FastAPI, HTTPException
from pydantic import BaseModel

app = FastAPI()

class Item(BaseModel):
	test: str = None
	is_done: bool = False

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

@app.get("/items/{item_id}")
def get_item(item_id: int) -> Item:
	if item_id < len(items):
		return items[item_id]
	else:
		raise HTTPException(status_code=404, detail=f"Item {item_id} not found.")

If you use a modeled object (like Item with Pydantic in our case), FastAPI expects it to be in the payload, not the url query parameter any more.

POST -H "Content-Type: application/json" -d '{"text":"apple"}' 'localhost:8000/items'

Response Model

Simply use the pydantic model in response_model argument in the route decorator:

@app.get("/items", response_model=list[Item])
def list_items(limit: int = 10):
	return items[0:limit]

Interactive docs

Just go to your route /docs or /redoc to see an interactive doc of your api.