What are FastAPI and Uvicorn? Beginner tutorial, GitHub projects, and response models

What FastAPI and Uvicorn are and why FastAPI needs Uvicorn, a beginner tutorial, GitHub examples, models, response models and PUT endpoint examples.

Presenting Annapurna on stage
Presenting Annapurna on stage

Key takeaways

  • FastAPI is a Python web framework for building APIs; Uvicorn is the ASGI server that runs it.
  • FastAPI defines your app; Uvicorn listens for HTTP requests and passes them to the app.
  • Use Pydantic models for request bodies and response models to validate and document data automatically.
  • The official tutorial and the full-stack template on GitHub are the best starting points.
  • Use PUT for full updates and PATCH for partial ones, with clear 404 handling.

FastAPI is a modern Python framework for building APIs, using type hints to validate data and generate interactive documentation automatically. Uvicorn is an ASGI web server that runs FastAPI apps, receiving HTTP requests and handing them to your code. You write the app with FastAPI and serve it with Uvicorn. FastAPI is the back end of my AI products, including the FaceVision embedding service, so this page covers both tools, a beginner tutorial, GitHub examples, models, response models and PUT endpoints.

What are FastAPI and Uvicorn?

FastAPI is a Python framework for building web APIs with automatic validation, serialisation and OpenAPI documentation, built on Starlette and Pydantic. Uvicorn is a lightweight, fast ASGI server that runs asynchronous Python web apps such as FastAPI.

Also asked as: what is fastapi and uvicorn

Together they form a common stack for Python back ends: FastAPI handles routes, validation and business logic; Uvicorn handles network connections and the HTTP protocol. FastAPI is popular for AI and machine learning services because Python dominates that ecosystem and async support handles many concurrent requests, such as streaming model responses. Both are open source and widely used in production.

Why does FastAPI need Uvicorn?

FastAPI is an application framework, not a server. It defines how to respond to requests but does not listen on a network port. An ASGI server such as Uvicorn accepts connections, parses HTTP and calls your FastAPI app.

ASGI, the Asynchronous Server Gateway Interface, is the standard connecting Python async servers and frameworks. Uvicorn is the most common choice, but alternatives such as Hypercorn and Granian also work. The fastapi dev and fastapi run commands use Uvicorn under the hood. In production, run Uvicorn with multiple workers, or behind a process manager, and put a reverse proxy in front for HTTPS.

What is the difference between FastAPI and Uvicorn?

FastAPI is the framework where you write endpoints, models and dependencies. Uvicorn is the server that runs the framework and handles HTTP connections. You need both: one defines behaviour, the other serves it.

An analogy: FastAPI is the restaurant's menu and kitchen, deciding what to make; Uvicorn is the front desk taking orders and delivering food. You can swap the server without changing your app, or run other ASGI frameworks on Uvicorn. Errors in validation or business logic come from your FastAPI code; errors about ports, workers or connections usually come from the server layer. In development, fastapi dev restarts the server whenever you save a file; in production, fastapi run or a Uvicorn command with several workers serves traffic without reloading.

What is a good FastAPI tutorial for beginners?

The official FastAPI tutorial is the best starting point: clear, example-driven and current. Install FastAPI, write a first endpoint, run it, and explore the automatic docs at /docs.

from fastapi import FastAPI
app = FastAPI()

@app.get("/hello/{name}")
def hello(name: str):
    return {"message": f"Hello, {name}"}

Run pip install "fastapi[standard]", then fastapi dev main.py, and open http://127.0.0.1:8000/docs. Next learn path and query parameters, request bodies with Pydantic, dependencies, database access, authentication and testing with TestClient. Build one small project as you go, such as a notes API with a database, so each chapter adds a real feature. Read error messages in the interactive docs, which show exactly which field failed validation and why.

Where can I find a FastAPI tutorial on GitHub?

The FastAPI repository on GitHub contains the documentation source with all tutorial examples, and the official full-stack FastAPI template shows a production-style project. Community collections list many more examples and libraries.

Also asked as: fastapi tutorial github

Useful repositories to study:

  • The FastAPI repository's docs examples, organised by topic.
  • The full-stack FastAPI template with PostgreSQL, authentication, tests and Docker.
  • "Awesome FastAPI" community lists of tools and projects.
  • Open-source apps built with FastAPI in your domain, such as ML serving.

Read the code alongside the tutorial: see how routers, dependencies and settings are organised in larger projects, then apply that structure to your own app.

What is a good example FastAPI project on GitHub?

The official full-stack FastAPI template is the best-known example: a FastAPI back end with SQLModel and PostgreSQL, JWT authentication, tests, a React front end, Docker Compose and deployment configuration.

Also asked as: example fastapi project github

When building your own example project for a portfolio, include: routers split by feature, Pydantic schemas, a database layer with migrations, authentication, background tasks, tests, Docker, and a README with setup steps and API docs screenshots. An AI-flavoured project, such as a document question-answering API with streaming responses and citations, shows modern skills. Keep secrets in environment variables and provide an .env.example file. Add a GitHub Actions workflow that runs tests on every push, which signals professional habits to anyone reviewing the repository.

What is a FastAPI model example?

In FastAPI, models are Pydantic classes that define data shapes. FastAPI uses them to validate request bodies, convert types and generate documentation automatically.

from pydantic import BaseModel, Field

class ItemIn(BaseModel):
    name: str = Field(min_length=1, max_length=100)
    quantity: int = Field(ge=0)
    tags: list[str] = []

@app.post("/items")
def create_item(item: ItemIn):
    return {"received": item}

If a client sends invalid data, such as a negative quantity, FastAPI returns a clear 422 error automatically. Separate input models from database models and output models so you never accidentally expose internal fields.

What is a FastAPI response model example?

A response model declares the shape of data an endpoint returns. FastAPI filters the output to that model, validates it and documents it, which prevents leaking fields such as password hashes.

class UserOut(BaseModel):
    id: int
    email: str

@app.get("/users/{user_id}", response_model=UserOut)
def get_user(user_id: int):
    user = db_get_user(user_id)   # may include hashed_password
    return user

Even if user contains extra fields, only id and email are returned. You can also use return type annotations instead of response_model. Use response_model_exclude_none=True to drop empty fields where helpful.

What is a FastAPI response example?

FastAPI endpoints can return dictionaries, Pydantic models or lists, which become JSON automatically, or explicit response classes for other formats, status codes and headers, such as JSONResponse, HTMLResponse, FileResponse and StreamingResponse.

from fastapi.responses import StreamingResponse

@app.get("/stream")
def stream():
    def gen():
        for word in ["Retrieval", "augmented", "generation"]:
            yield word + " "
    return StreamingResponse(gen(), media_type="text/plain")

Streaming responses are how AI apps show answers as they are generated. Set status codes with status_code=201 on decorators, and add response examples in the OpenAPI docs to help API consumers.

What is a FastAPI PUT example?

A PUT endpoint replaces a resource with new data. Take the ID from the path and the full updated object from the request body, return 404 if it does not exist, and return the updated resource.

from fastapi import HTTPException

@app.put("/items/{item_id}", response_model=ItemIn)
def update_item(item_id: int, item: ItemIn):
    if item_id not in items_db:
        raise HTTPException(status_code=404, detail="Item not found")
    items_db[item_id] = item
    return item

Use PATCH for partial updates, with a model whose fields are optional and item.model_dump(exclude_unset=True) to apply only provided fields. Add authentication so only permitted users can modify resources. Write a test for each case, a successful update, a missing item and invalid data, so changes to the endpoint never break silently.

Sources

  1. FastAPI, documentationfastapi.tiangolo.com
  2. FastAPI, Tutorial and User Guidefastapi.tiangolo.com
  3. FastAPI, repositorygithub.com
  4. FastAPI, Full Stack templategithub.com
  5. Pydantic, documentationdocs.pydantic.dev
Pranjul Rathour
Pranjul Rathour
GenAI Engineer · India

GenAI engineer and AI product builder with 2+ years shipping production-grade AI systems: RAG pipelines, fine-tuned LLMs, hybrid retrieval and multi-modal apps across vision, speech and OCR, architected end to end from ingestion to deployment. Leads engineering for SCULT INDIA's 14-member team, founded the 500+ member TechVerse Enclave community and has mentored 200+ students. Three hackathon first prizes: Changethon 2025 (IIT Roorkee), Product Genesis at Vividhotsava 2025 (CSJMU) and BYTEBATTLE (MeetKats).

Open to GenAI roles, hackathon judging, mentorship sessions and guest talks at colleges. For campus sessions the inviting institution covers the visit end to end: travel (a First AC train ticket for journeys up to five hours, a flight for anything longer), accommodation, meals, and pickup and drop; the honorarium and workshop fees are negotiable on WhatsApp or on the call, and requests are welcome from institutions that can cover the visit this way. Email pranjulrathour41@gmail.com.

Keep reading

More on Shipping AI apps

All Shipping AI apps guides →
Campus talks · hackathon judging · mentoring

Want this as a live session at your college?

Open to GenAI roles, hackathon judging, mentorship sessions and guest talks at colleges. For campus sessions the inviting institution covers the visit end to end: travel (a First AC train ticket for journeys up to five hours, a flight for anything longer), accommodation, meals, and pickup and drop; the honorarium and workshop fees are negotiable on WhatsApp or on the call, and requests are welcome from institutions that can cover the visit this way.

Pranjul Rathour, GenAI engineer in India