Learn to Code
All tracks
Learn to Code

Free lessons from scratch to pro — every language, databases and DevOps.

AboutContactPrivacy PolicyTerms of Use

Your progress is saved in this browser. © 2026 Learn to Code

DJ
Django & FastAPI
0/12 completed
Beginner
How Python web frameworks workYour first FastAPI appRequest bodies and Pydantic models
Intermediate
FastAPI with a databaseDependencies, routers and testingDjango: projects, apps and the ORMDjango views, URLs and templatesForms, the admin and class-based views
Advanced
APIs with Django REST frameworkAuthentication in Django and FastAPIBackground tasks and async
Pro
Deploying Python web apps
Tracks / Django & FastAPI / Beginner

Your first FastAPI app

FastAPI builds APIs from ordinary Python functions with type hints. From those hints it validates incoming data, converts types, writes error messages and generates interactive documentation, all automatically. It's one of the fastest-growing Python frameworks.

Hello, FastAPI

Python · editable
  • app = FastAPI() creates the application.
  • @app.get("/") is a path operation decorator: it registers the function below it for GET requests to /.
  • Returning a dict (or list, or Pydantic model) sends it as JSON.

On your computer, save the app part as main.py and run fastapi dev main.py. Open http://127.0.0.1:8000/ for the response and http://127.0.0.1:8000/docs for interactive docs. In these editors, the "Try it" section at the bottom plays the role of the browser: it calls the app through httpx, exactly as FastAPI's own testing guide does.

Path parameters

Parts of the URL can be variables. Declare them in the path with {} and as function parameters with a type:

Python · editable

Look at /products/mug: because product_id is an int, FastAPI rejected the text with a 422 and a precise explanation. Your function never ran. And for /products/2, FastAPI converted the string "2" from the URL into the integer 2.

HTTPException stops the request and returns an error status with a detail message.

Query parameters

Function parameters that aren't in the path become query parameters (?key=value). Give them defaults to make them optional:

Python · editable

FastAPI understood sort_by_price=true as a boolean (it also accepts 1, yes and on), and turned max_price=cheap into a clear validation error.

Adding rules with Query and Path

Python · editable

ge means "greater than or equal", le "less than or equal". All three errors were reported at once.

async or not?

Path operations can be ordinary def functions or async def coroutines:

python
@app.get("/slow-report")
def report():                  # blocking work (most database libraries): FastAPI runs it in a thread pool
    return build_report()

@app.get("/weather")
async def weather():           # await-able work (httpx, async database drivers)
    async with httpx.AsyncClient() as client:
        r = await client.get("https://api.example.com/weather")
    return r.json()

Use async def when the code inside awaits things; otherwise plain def is fine and safe. Never call blocking functions (like time.sleep or requests.get) inside async def: they freeze every other request.

Automatic documentation

FastAPI generates an OpenAPI description of your API from the code, and serves it with two interactive UIs: Swagger UI at /docs and ReDoc at /redoc. The raw spec is at /openapi.json:

Python · editable

The docstring became the description, and the type hints became parameter types. The documentation can't drift from the code, because it is the code.

Practice

  1. Add GET /products/{product_id}/price?currency=EUR that converts the price with a fixed rate (1 USD = 0.92 EUR), allowing only USD and EUR (use Literal["USD", "EUR"]).
  2. Add a limit query parameter to /products that must be between 1 and 50.
  3. Return a 404 with detail="Category not found" when category isn't one of the known ones.
✎ Check your understanding

1.In def get_item(item_id: int) for the path /items/{item_id}, what happens for /items/abc?

2.How do you make a query parameter optional?

3.Where does FastAPI serve interactive documentation by default?

← How Python web frameworks work