Skip to content
Software Development

FastAPI Basics: Build Your First Typed Python API

Build a typed FastAPI blog-post API with GET, POST, validation, error handling, and automatic OpenAPI documentation.

CodingBowl··10 min read
Photo by Markus Spiske on Unsplash
APIASGIDjangoFastAPIPydanticPython

FastAPI is a Python web framework for building APIs with type hints. It combines readable route declarations with Pydantic validation and automatic OpenAPI documentation.

This article builds a small, runnable blog-post API. The data stays in memory so the example focuses on FastAPI. A later article will explain how FastAPI can work with the existing Django blog and a React frontend on a separate domain.

The HTTP concepts that matter

You do not need to learn all of HTTP before writing an API, but these ideas are important:

Concept Meaning here
GET Read resources without changing them.
POST Send data to create a resource.
Path parameter A value in the URL, such as /posts/1.
Query parameter Optional URL data, such as /posts?limit=10.
Request body JSON sent with a POST request.
Status code A result signal such as 200, 201, 404, or 422.
JSON The structured format used by requests and responses.

An API is a contract: the client sends data in an expected shape, and the server returns a predictable response and status code.

Create the project

python -m venv .venv
source .venv/bin/activate
python -m pip install fastapi uvicorn

On Windows PowerShell, activate the environment with .venv\\Scripts\\Activate.ps1. Create a file named main.py.

Define typed models

from datetime import date

from pydantic import BaseModel, Field


class BlogPost(BaseModel):
    id: int
    title: str = Field(min_length=1, max_length=180)
    excerpt: str = Field(min_length=1, max_length=320)
    published_at: date


class BlogPostCreate(BaseModel):
    title: str = Field(min_length=1, max_length=180)
    excerpt: str = Field(min_length=1, max_length=320)
    published_at: date

The annotations document intent and give FastAPI the information it needs to validate JSON and describe the API in OpenAPI.

Create the application

Add the application and a temporary in-memory collection:

from fastapi import FastAPI, HTTPException, Query


app = FastAPI(title='Blog Posts API', version='0.1.0')

posts: list[BlogPost] = [
    BlogPost(
        id=1,
        title='FastAPI Basics',
        excerpt='A typed API built with Python.',
        published_at=date(2026, 11, 17),
    )
]

Restarting the server resets this list. A real application would replace it with a database or another persistent store.

Add GET endpoints

Use a query parameter to limit a collection response:

@app.get('/posts', response_model=list[BlogPost])
def list_posts(limit: int = Query(default=10, ge=1, le=50)) -> list[BlogPost]:
    return posts[:limit]

The ge=1 and le=50 rules reject unsupported limits. The response model controls the response shape and documents it in OpenAPI.

curl 'http://127.0.0.1:8000/posts?limit=5'

For one resource, put its identifier in the path:

@app.get('/posts/{post_id}', response_model=BlogPost)
def get_post(post_id: int) -> BlogPost:
    for post in posts:
        if post.id == post_id:
            return post
    raise HTTPException(status_code=404, detail='Post not found')

The int annotation validates the path value before the function runs. A missing post is different: the request is valid, but the resource does not exist, so the handler returns 404 Not Found.

Add a POST endpoint

The request body is declared with BlogPostCreate:

@app.post('/posts', response_model=BlogPost, status_code=201)
def create_post(payload: BlogPostCreate) -> BlogPost:
    next_id = max((post.id for post in posts), default=0) + 1
    post = BlogPost(id=next_id, **payload.model_dump())
    posts.append(post)
    return post

Run the server:

uvicorn main:app --reload

Create a post:

curl -X POST 'http://127.0.0.1:8000/posts' \\
  -H 'Content-Type: application/json' \\
  -d '{
    "title": "Using Pydantic for API input",
    "excerpt": "Validate request data before application code uses it.",
    "published_at": "2026-11-18"
  }'

The endpoint returns 201 Created and the new resource, including its server-assigned identifier.

Validation and errors

An invalid request such as an empty title or "published_at": "not-a-date" returns 422 Unprocessable Entity. The response identifies the fields that failed validation.

The useful distinction is:

  • 404 means the request shape was valid, but the requested post was not found.
  • 422 means the request data did not satisfy the endpoint's validation rules.

Automatic API documentation

With the server running, open /docs for interactive Swagger UI or /redoc for ReDoc. FastAPI builds these views from route declarations, type hints, Pydantic models, response models, and status codes.

Synchronous and asynchronous handlers

The example uses normal def handlers because its in-memory list does not perform asynchronous I/O. A simple health endpoint is also synchronous:

@app.get('/health')
def health() -> dict[str, str]:
    return {'status': 'ok'}

Use async def when the handler needs to await an async database driver, HTTP client, or other async operation. Do not add async merely because it looks modern: a synchronous blocking call inside an async handler can still block the event loop.

From this example to a real project

A single file is useful for learning. A larger service can separate routing, schemas, and application operations:

app/
├── main.py
├── api/
│   └── routes_posts.py
├── schemas/
│   └── posts.py
└── services/
    └── posts.py

APIRouter can group related routes, Pydantic models can remain in a schemas module, and services can hold application operations. The goal is to keep routing, validation, and business operations easy to test independently.

What changes when Django is involved?

This article intentionally uses an in-memory list and does not modify the existing Django project. In the next article, the same API ideas will be applied to a separate React frontend:

  • Django remains responsible for the existing site, admin, users, and database models.
  • FastAPI exposes public blog endpoints and protected user endpoints.
  • React calls FastAPI from a different domain, so CORS must be restricted to the approved frontend origin.
  • Token authentication must be defined explicitly; Django session cookies do not automatically become FastAPI authentication.
  • The existing Django Post model can be read through a carefully defined API schema.

Summary

FastAPI turns Python type hints into practical API behavior: route decorators define endpoints, annotations validate URL data, Pydantic models validate JSON, exceptions communicate resource errors, and OpenAPI documentation is generated from the same declarations used by the application.