FastAPI is a modern Python framework for building APIs. Automatic documentation, type hints, high performance.
Installation
pip install fastapi uvicorn
First Application
# main.py
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def root():
return {"message": "Hello, World!"}
@app.get("/items/{item_id}")
def get_item(item_id: int, q: str | None = None):
return {"item_id": item_id, "q": q}
uvicorn main:app --reload
Running and Documentation
- Application:
http://127.0.0.1:8000 - Swagger UI:
http://127.0.0.1:8000/docs - ReDoc:
http://127.0.0.1:8000/redoc
Path Parameters
@app.get("/users/{user_id}")
def get_user(user_id: int): # automatic type validation
return {"user_id": user_id}
@app.get("/files/{file_path:path}") # path with /
def get_file(file_path: str):
return {"path": file_path}
Query Parameters
@app.get("/tasks/")
def list_tasks(
status: str | None = None,
limit: int = 20,
offset: int = 0,
):
return {"status": status, "limit": limit, "offset": offset}
GET /tasks/?status=todo&limit=10
POST with Request Body
from pydantic import BaseModel
class TaskCreate(BaseModel):
title: str
status: str = "todo"
priority: int = 1
@app.post("/tasks/", status_code=201)
def create_task(task: TaskCreate):
return {"id": 1, **task.model_dump()}
HTTP Methods
@app.get("/tasks/{id}") # retrieve
@app.post("/tasks/") # create
@app.put("/tasks/{id}") # replace
@app.patch("/tasks/{id}") # partial update
@app.delete("/tasks/{id}") # delete
💬 Comments (0)
No comments yet
Be the first to share your opinion about this article!