Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

FastAPI
  • FastAPI Hello World: Routes, uvicorn and the Free Swagger Page
  • RESTful API Basics: Resources, Methods, Stateless Requests and Status Codes
  • Django, FastAPI or Flask? The Same Blog Feature in Three Shapes, and How to Choose
  • One Blog, Three Frameworks: Routing, Models, Templates and Layout in Django, FastAPI and Flask
  • One Request, Two Answers: the Same Post as an HTML Page and as JSON
  • What FastAPI Is: Starlette, Pydantic, uvicorn and What async def Really Gives You
  • Building a Blog with an AI Coding Agent: Plan Mode, a Master Prompt and the First Review
  • Handing a Figma Design to an AI Agent: Compare the Files, Then Review the Change
  • Inside a FastAPI Blog: Every Folder and File an AI Agent Built, and What to Question
  • Swagger UI and OpenAPI in FastAPI: Reading the Contract Your Code Writes
  • POST, PUT and DELETE in FastAPI: Choosing 201, 200, 204 and 404 on the Server
  • Paging, Sorting and Filtering a REST API in FastAPI
  • API Versioning in FastAPI with an API-Version Header
  • Idempotent REST Methods, HATEOAS and the Maturity Model: Which Requests Are Safe to Repeat
  • A FastAPI REST API End to End: One App Visit, Seven Requests
  • The Book API in FastAPI: A Contract a React Client Can Rely On
  • A React Client for a FastAPI API: The CORS Wall, CORSMiddleware and the Vite Proxy
  • FastAPI Request and Response Models with Pydantic: Design the JSON on Purpose
  • FastAPI Path, Query and Body Parameters: Reading a 422, response_model and Depends
  • Validation and Problem Details in FastAPI: From a 422 to One Error Shape for the Whole API
  • FastAPI with SQLAlchemy Models and Alembic Migrations: A Table from a Class, a Session per Request
  • From a List to a Database in FastAPI: Route, Service, Repository and the SQL SQLAlchemy Sends
  • Docker Compose: Run a FastAPI App and Postgres From One File
  • Docker Health Checks, Networks and Resource Limits: Up Is Not Enough
  • How a Request and a Login Flow Through a FastAPI Blog: Depends, bcrypt, a Signed Session Cookie and async def
  • Enterprise Integration for an AI App: One Adapter per Edge for SSO, the CRM, a Legacy CSV and Webhooks
  1. Blog
  2. /
  3. FastAPI
  4. /
  5. Fundamentals

What FastAPI Is: Starlette, Pydantic, uvicorn and What async def Really Gives You

FastAPI in one small Airport Board app: Starlette for the web side, Pydantic for the data, uvicorn as the server. Type hints turn gate=abc into a 422, the OpenAPI file and /docs page come for free, and async def only helps when something inside awaits.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Fundamentals

What you will learn

  • Name the two libraries FastAPI is built on and the server that runs it
  • Use type hints and a Pydantic model so bad input gets a 422 before your code runs
  • Read the OpenAPI description and the /docs page FastAPI writes for you
  • Explain when async def helps and when it does nothing

Before you start

  • Python functions and type hints
  • Decorators in Python

Every API has jobs that have nothing to do with your actual idea. You check that a gate number really is a number. You write a page that explains your routes, and it goes out of date the day the code changes. You turn data into JSON and back, again and again. And while a request waits for a database, the worker handling it just sits there.

FastAPI's idea is simple: you describe your data once, with type hints, and it does that glue for you. We'll see what that means with one small app called Airport Board, in a single main.py, plus a check script that calls it.

What FastAPI is made of

FastAPI is a Python framework for building APIs, and it stands on two other libraries:

  • Starlette handles the web side: routes, requests and responses.
  • Pydantic handles the data side: checking values and turning them into JSON.

Your code sits on top. You write normal Python functions with type hints, and FastAPI connects them to the other two. Underneath it all is a server, uvicorn, which takes requests from the network and hands them to your app. The two talk through a standard called ASGI, the Asynchronous Server Gateway Interface.

A request comes from the client to uvicorn, the server. uvicorn passes it over ASGI to the FastAPI app. FastAPI uses Starlette for the web side and Pydantic for the data side, and calls your functions with type hints on top. Client browser, test uvicorn the server Your code plain functions with type hints FastAPI connects your code to both below Starlette routes, requests Pydantic check data, JSON ASGI
FastAPI isn't the server. It's the app, and uvicorn runs it.

Your first route

Here's the whole app, main.py:

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI(title="Airport Board")


class Flight(BaseModel):
    code: str
    gate: int
    on_time: bool = True


@app.get("/")
async def home():
    return {"message": "Welcome to the airport"}


@app.get("/flights/{code}")
async def get_flight(code: str, gate: int = 12) -> Flight:
    return Flight(code=code, gate=gate)

app = FastAPI(title="Airport Board") makes the app. @app.get("/") is a decorator: when a GET request comes for the home path, call the function below. home returns a normal Python dictionary, and FastAPI turns it into JSON for you.

To call it without starting a server, check_app.py uses FastAPI's test client:

import json

from fastapi.testclient import TestClient

from main import app

client = TestClient(app)

resp = client.get("/")
print("GET / ->", resp.status_code)
print(resp.json())
GET / -> 200
{'message': 'Welcome to the airport'}

uvicorn serves the app

To serve it over the network, run uvicorn. main is the file and app is the object inside it:

uvicorn main:app --port 8765
INFO:     Started server process [3636]
INFO:     Waiting for application startup.
INFO:     Application startup complete.
INFO:     Uvicorn running on http://127.0.0.1:8765 (Press CTRL+C to quit)
INFO:     127.0.0.1:55264 - "GET / HTTP/1.1" 200 OK

A request comes in for /. uvicorn receives it and hands it to the app through ASGI. FastAPI finds the route and calls home. The dictionary goes back as JSON, and uvicorn sends the response and logs one line. The step-by-step install and first run are in FastAPI Hello World.

Declare the shape with Pydantic

Flight inherits from Pydantic's BaseModel. It has three fields: code is a string, gate is an int, and on_time is a bool that defaults to True. That's the shape of a flight, written once.

In get_flight, code is in the path (the curly braces), so it comes from the URL. gate isn't in the path, so FastAPI reads it from the query string, with 12 as the default. The arrow, -> Flight, says the function returns a Flight.

resp = client.get("/flights/AB123")
print("GET /flights/AB123 ->", resp.status_code)
print(resp.json())

resp = client.get("/flights/AB123?gate=7")
print("GET ...?gate=7 ->", resp.status_code)
print(resp.json())
GET /flights/AB123 -> 200
{'code': 'AB123', 'gate': 12, 'on_time': True}
GET ...?gate=7 -> 200
{'code': 'AB123', 'gate': 7, 'on_time': True}

With ?gate=7, the gate comes back as the number 7, not the text "7". The type hint did that conversion.

A wrong value never reaches your code

Now a bad boarding pass: gate=abc.

resp = client.get("/flights/AB123?gate=abc")
print("GET ...?gate=abc ->", resp.status_code)
print(json.dumps(resp.json(), indent=2))
GET ...?gate=abc -> 422
{
  "detail": [
    {
      "type": "int_parsing",
      "loc": [
        "query",
        "gate"
      ],
      "msg": "Input should be a valid integer, unable to parse string as an integer",
      "input": "abc"
    }
  ]
}

FastAPI tried to turn abc into an int, couldn't, and answered 422 Unprocessable Entity. get_flight never ran. The body says what went wrong (int_parsing), where (query, then gate) and what you sent. You wrote zero checks for this. Path, query and body parameters get their own article: FastAPI Path, Query and Body Parameters.

OpenAPI, written for you

FastAPI reads your routes and models and writes a description of the whole API at /openapi.json. The rest of check_app.py reads it:

spec = client.get("/openapi.json").json()
print("openapi.json keys:", list(spec))
print("openapi:", spec["openapi"])
print("title:", spec["info"]["title"])
print("paths:", list(spec["paths"]))
print("schemas:", list(spec["components"]["schemas"]))
print(json.dumps(
    spec["components"]["schemas"]["Flight"], indent=2
))
openapi.json keys: ['openapi', 'info', 'paths', 'components']
openapi: 3.1.0
title: Airport Board
paths: ['/', '/flights/{code}']
schemas: ['Flight', 'HTTPValidationError', 'ValidationError']
{
  "properties": {
    "code": {
      "type": "string",
      "title": "Code"
    },
    "gate": {
      "type": "integer",
      "title": "Gate"
    },
    "on_time": {
      "type": "boolean",
      "title": "On Time",
      "default": true
    }
  },
  "type": "object",
  "required": [
    "code",
    "gate"
  ],
  "title": "Flight"
}

Our title is there, both paths are there, and Flight lists code and gate as required, because only on_time has a default. The two validation schemas next to it are FastAPI's own, for the 422 error we just saw. OpenAPI is an open standard, so a front end, another team or an AI tool can read this one file and know how to call your API.

Interactive docs at /docs

docs = client.get("/docs")
print("GET /docs ->", docs.status_code)
print(docs.headers["content-type"])
print("Swagger page:", "swagger-ui" in docs.text)
GET /docs -> 200
text/html; charset=utf-8
Swagger page: True

/docs is a Swagger UI page. It reads openapi.json and draws every route as a row you can open, fill in and send. Because the page is built from the code, it changes when the code changes.

What async def really gives you

Both routes are async def. In FastAPI, one worker (the event loop) can look after many requests. When a request reaches an await, for example while it waits for another service, the worker switches to the next request, and comes back when the answer arrives.

The limit: async def only helps when the work inside actually awaits. If the code does something slow that doesn't await, a blocking call, the worker is stuck and every other request waits too. Our home waits for nothing, so here async changes nothing. If you write a plain def instead, FastAPI runs it on a separate thread, so a slow plain function doesn't hold up the others.

This matters as soon as a database is involved. You'll see it timed in FastAPI with SQLAlchemy Models and Alembic Migrations, and checked against the real blog in How a Request and a Login Flow Through the FastAPI Blog.

Why this helps when an AI agent writes the code

Type hints and models are a contract: they say what comes in and what goes out, so an AI coding agent has less to guess. A sample prompt in Role, Context, Task and Format:

You're a FastAPI developer. main.py has a Flight model and two routes. Add a route that returns only a flight's code and on_time, with type hints. Show only the changed lines.

When the diff comes back, check three things. Does the new route have type hints? Does it use the model where it should? Does it show up in /docs?

Common mistakes

  • Thinking FastAPI is the server. It's the app. uvicorn is the server, and the two talk over ASGI.
  • Writing validation by hand. A type hint like gate: int already turns abc away with a 422.
  • Expecting async def to make code fast. It only helps when the slow work inside is awaited.
  • Editing docs by hand. /openapi.json and /docs are built from the code, so change the code instead.

Quick recap

PieceJobIn Airport Board
Starletteroutes, requests, responses@app.get(...)
Pydanticcheck data, build JSONFlight, the 422 for gate=abc
uvicornthe ASGI serveruvicorn main:app --port 8765
OpenAPIdescription of the API/openapi.json, version 3.1.0
Swagger UIinteractive docs/docs
async deffrees the worker at each awaitno effect here, nothing awaits

Try it yourself

Add a terminal field to Flight with a default value, run python check_app.py again, and find the new field in the Flight schema it prints.

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in FastAPI · 6 of 26

Previous
One Request, Two Answers: the Same Post as an HTML Page and as JSON
Next post
Building a Blog with an AI Coding Agent: Plan Mode, a Master Prompt and the First Review

Related course on Udemy

The Python Architect Masterclass: Full Stack to AI Engineer

Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)

Related posts

FastAPI Hello World: Routes, uvicorn and the Free Swagger Page

The smallest FastAPI app: two routes in main.py, started with uvicorn. Follow one request from the browser to the route table and back as JSON, see a 404, and try the routes on the free Swagger page at /docs.

RESTful API Basics: Resources, Methods, Stateless Requests and Status Codes

An API is the waiter between your program and a server. REST gives each resource an address and uses the HTTP method for the action. Send GET, POST, PUT, PATCH and DELETE to a tiny local server with urllib, see why requests are stateless, and read 200, 201, 204, 400 and 404.

Django, FastAPI or Flask? The Same Blog Feature in Three Shapes, and How to Choose

One small project lists two blog posts three times: as a Django view, a Flask route and a FastAPI endpoint. See each shape with its real output, what each framework includes, and a three-question way to choose.

One Blog, Three Frameworks: Routing, Models, Templates and Layout in Django, FastAPI and Flask

The same blog built in Django, FastAPI and Flask, compared line by line: the list route, the Post model, the template loop, the project layout and the extras, with a ROSETTA map you can use to port a feature with AI.

On this page

  • What FastAPI is made of
  • Your first route
  • uvicorn serves the app
  • Declare the shape with Pydantic
  • A wrong value never reaches your code
  • OpenAPI, written for you
  • Interactive docs at /docs
  • What async def really gives you
  • Why this helps when an AI agent writes the code
  • Common mistakes
  • Quick recap
  • Try it yourself
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

The Python Architect Masterclass: Full Stack to AI Engineer

Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.