Skip to content

Build a Python Web API with FastAPI: Routes, Path and Query Parameters, Pydantic and /docs

NeedMyTools Academy

Sign in free to read the full lesson

Sign in or create a free account

Free forever. No card, no paywall.

This is the final project of the Python course: everything so far, functions, dictionaries, classes and exceptions, comes together in a small web API that other programs can call. FastAPI is a popular Python framework for this. You write ordinary functions with type hints, and FastAPI turns them into HTTP endpoints that read parameters, check the incoming data, send JSON back and describe themselves in interactive documentation. A web server cannot run inside this page, so this lesson shows real output instead: we ran the code below on 4 December 2026 with Python 3.13, FastAPI 0.165.1, Pydantic 2.14.4 and Uvicorn 0.55.0, and called it with curl.

Quick answer

Install with pip install "fastapi[standard]", create app = FastAPI() in main.py, and decorate functions with @app.get("/path") or @app.post(...). Parameters in the path, such as {product_id}, and extra function arguments, which become query parameters, are converted to the hinted types; bad input gets an automatic 422. Raise HTTPException(status_code=404) for missing items. A Pydantic BaseModel describes and validates the JSON body. Run with fastapi dev main.py and open /docs.

45 min read and practice · Content checked on 4 December 2026

In this lesson you will

  • Create GET routes with path and query parameters in FastAPI
  • Return the right status codes with HTTPException and status_code
  • Validate JSON bodies with Pydantic models and read the generated docs

Install, first routes and running the server

Create a folder and a virtual environment with python -m venv .venv, activate it, and run pip install "fastapi[standard]". The [standard] part adds Uvicorn, the server that actually listens for requests, and the fastapi command. In main.py, app = FastAPI(title=...) creates the application, and each decorator such as @app.get("/api/products") registers the function under it for that method and path. Whatever the function returns, a list, a dictionary or a model, is converted to JSON automatically.

fastapi dev main.py starts a development server on port 8000 that reloads when you save the file. Function arguments that are not in the path become query parameters: max_price: float | None = None is optional, so /api/products returned both products and ?max_price=40 returned only saffron. {product_id} in the path is passed to the function, and because it is hinted as int, FastAPI converts the text 2 into the number 2 before your code runs. A missing product raises HTTPException, which FastAPI turns into a 404 response with a JSON detail message.

Example: A product API with two GET routes
main.py
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, Field

app = FastAPI(title="Gulf Shop API")


class ProductIn(BaseModel):
    name: str = Field(min_length=2)
    price: float = Field(gt=0)


class Product(ProductIn):
    id: int


products = {
    1: Product(id=1, name="Saffron 5 g", price=38),
    2: Product(id=2, name="Dates 1 kg", price=45),
}


@app.get("/api/products")
def list_products(max_price: float | None = None) -> list[Product]:
    items = list(products.values())
    if max_price is not None:
        items = [p for p in items if p.price <= max_price]
    return items


@app.get("/api/products/{product_id}")
def get_product(product_id: int) -> Product:
    if product_id not in products:
        raise HTTPException(status_code=404, detail="Product not found")
    return products[product_id]
Real output: terminal, fastapi dev main.py (we used --port 8123; the default is 8000)
 ⚡️ Starting FastAPI in development mode
 
 🐍 Using import string: main:app
 
 🌐 Server started at http://127.0.0.1:8123
    Documentation at http://127.0.0.1:8123/docs
 
  Logs:
 
INFO:     Uvicorn running on http://127.0.0.1:8123 (Press CTRL+C to quit)
INFO:     Started reloader process [821] using WatchFiles
INFO:     Started server process [827]
INFO:     Waiting for application startup.
INFO:     Application startup complete.
Real output: four curl requests (status code shown after each body)
$ curl .../api/products
[{"name":"Saffron 5 g","price":38.0,"id":1},{"name":"Dates 1 kg","price":45.0,"id":2}] 200
$ curl ".../api/products?max_price=40"
[{"name":"Saffron 5 g","price":38.0,"id":1}] 200
$ curl .../api/products/2
{"name":"Dates 1 kg","price":45.0,"id":2} 200
$ curl .../api/products/9
{"detail":"Product not found"} 404

The URL is shortened to ... for http://127.0.0.1:8123, and one "Will watch for changes" line with our folder path was removed from the server output. The price 38 came back as 38.0 because the model declares price: float.

Sign in free to read the full lesson

You are reading the free preview. Create a free account (it takes one minute, no password) to unlock the rest of this lesson and track your progress.

Unlocks after sign-in:

  • 2 more sections with live code examples
  • Common mistakes to avoid
  • Hands-on coding exercise with automatic checks
  • Practice quiz and the graded lesson test
Sign in or create a free account

Free forever. No card, no paywall.

Questions people ask

FastAPI, Flask or Django: which should I learn?

For JSON APIs, FastAPI gives validation and docs with little code. Flask is smaller and older, with many tutorials. Django is a full framework with an admin panel, user accounts and an ORM, which suits large websites with server-rendered pages.

Why can I not run FastAPI in this page like the other examples?

An API needs a server process listening on a network port, and a browser tab cannot open one. That is why this lesson shows recorded output. Pydantic models alone do work in the browser, so you can test validation rules on earlier lesson pages.

Should my FastAPI functions be async?

Only when they await async libraries, such as an async database driver or httpx. Plain def functions are fine; FastAPI runs them in a thread pool so they do not block other requests.

How do I connect FastAPI to a database?

The FastAPI documentation shows SQLModel with SQLite as a starting point, and the same code works with PostgreSQL. Keep the Pydantic models for input and output and let the database replace the products dictionary.

How do I let a website on another domain call my API?

Add CORSMiddleware with the exact origins you trust, such as your front end address. The CORS lesson in the HTTP and APIs course explains why the browser blocks the call until the server allows it.

Sources

Facts in this lesson were checked against these official pages on 4 December 2026.

Code examples stay in English and run in a sandbox on your device. If you spot a mistake, tell us through the contact page.