PYTHON WEB APIS

FastAPI Tutorials

FastAPI lets you build a typed, documented Python API with very little code. This learning path takes you from your first endpoint to databases, login and production security.

  • 8 topic areas
  • 0.162 FastAPI tested
  • 3.12 Python tested
A validated POST endpoint in 12 linesBuild your first API

What FastAPI is for

FastAPI is a Python framework for building web APIs. You describe each endpoint with normal Python type hints, and FastAPI uses them to validate requests, convert data and write the API documentation for you.

Send text where a number belongs and the request above comes back as a 422 with the exact field and reason, and you did not write a single if statement. It runs on Starlette and Pydantic, and it supports both regular and async routes.

Install FastAPI and run it

Create a virtual environment, install FastAPI with its standard extras, and start the development server from the folder that holds main.py.

The dev server reloads when you save a file. Your interactive docs are ready at /docs without any extra code.

Keep the quotes around "fastapi[standard]". Some shells treat the square brackets as a pattern.

Four commands to a running APIFull setup guide

Your learning path

Learn FastAPI in this order

Each stage builds on the one before it, so follow them in order if you are new to APIs.

  1. 1

    Build your first API

    Install FastAPI, then create routes with path and query parameters.

  2. 2

    Validate your data

    Use Pydantic models for request bodies and responses.

  3. 3

    Connect a database

    Build a full CRUD API, starting with SQLite.

  4. 4

    Add login and security

    Add JWT login, protected routes and role checks.

  5. 5

    Go real-time

    Add background tasks, file uploads and WebSockets.

Quick reference

FastAPI at a glance

The patterns you will use in almost every project.

TaskCodeWorth knowing
Read a URL value@app.get("/items/{item_id}")Type hints convert and validate it.
Read a query valuedef f(q: str | None = None)A default makes it optional.
Accept JSONdef f(order: Order)Bad input returns a 422.
Set a status code@app.post("/x", status_code=201)Shown in the docs too.
Return an errorraise HTTPException(404)Stops the route right away.
Share logicDepends(get_db)Works on routes and routers.

Every tutorial, by topic

FastAPI tutorials by topic

Linked titles are ready to read. Grey titles are on the way and will be linked as they go live.

Getting Started and Routing

20

Install it, run it, and build every kind of endpoint.

FastAPI Tutorial for BeginnersInstall FastAPI and Create Your First APIFastAPI Project Structure for BeginnersRun a FastAPI Application with UvicornCreate GET EndpointsCreate POST EndpointsCreate PUT and PATCH EndpointsCreate DELETE EndpointsFastAPI Path ParametersFastAPI Query ParametersSend JSON ResponsesReturn Custom Status CodesUse FastAPI Interactive API DocumentationCustomize Swagger UIAdd Tags to FastAPI EndpointsOrganize Routes with FastAPI APIRouterCreate a Health Check EndpointAdd a Root EndpointCreate a REST APIFastAPI vs Flask

Pydantic Models and Validation

15

Define the data you accept and the data you return.

FastAPI Request Body Validation with PydanticFastAPI Response ModelsCreate Pydantic ModelsValidate Email, Password, and URL FieldsMake Fields Optional in FastAPI Request ModelsUse Nested Pydantic ModelsValidate Lists and DictionariesSet Default Values in FastAPI Request ModelsExclude Fields from FastAPI ResponsesUse Pydantic Field ValidatorsHandle Validation ErrorsFastAPI Request Model vs Response ModelUse EnumsReturn Different Response ModelsCreate Reusable Pydantic Schemas

Dependency Injection

4

Share logic between routes with Depends.

FastAPI Dependency InjectionCreate a Reusable DependencyUse Dependencies for Database SessionsAdd Global Dependencies

Middleware

4

Run code around every request and response.

FastAPI Middleware Tutorial with ExamplesAdd CORS MiddlewareAdd Custom Headers with FastAPI MiddlewareLog Requests and Responses

Error Handling and Lifespan

7

Return clean errors and manage startup and shutdown.

FastAPI Error Handling TutorialRaise HTTP ExceptionsCreate a Custom Exception HandlerReturn Custom Error ResponsesHandle 404 ErrorsHandle Unhandled ExceptionsFastAPI Lifespan Events

Databases and CRUD

20

SQLite, PostgreSQL, MySQL, SQLAlchemy, SQLModel and Alembic.

Build a FastAPI CRUD API with SQLiteBuild a FastAPI CRUD API with PostgreSQLBuild a FastAPI CRUD API with MySQLFastAPI SQLAlchemy Tutorial for BeginnersFastAPI SQLModel Tutorial for BeginnersFastAPI SQLAlchemy 2.0 CRUD ExampleConnect FastAPI to PostgreSQLConnect FastAPI to MySQLCreate Database TablesCreate a Database Session DependencyCreate Database Models with SQLAlchemy and FastAPICreate Database Models with SQLModel and FastAPIFastAPI Async SQLAlchemy TutorialUse Async PostgreSQLUse Alembic MigrationsCreate and Run Alembic MigrationsAdd Pagination to a FastAPI CRUD APIAdd Filtering to FastAPI EndpointsAdd Sorting to a FastAPI CRUD APIUse Repository Pattern

Authentication and Security

20

JWT, OAuth2, roles, social login and production hardening.

FastAPI JWT Authentication Tutorial for BeginnersCreate a Login API with JWTProtect FastAPI Endpoints with JWT TokensCreate a User Registration APIHash Passwords in FastAPI with bcryptImplement OAuth2 Password FlowAdd Refresh TokensCreate Role-Based Access ControlCreate Permission-Based Access ControlSecure FastAPI APIs with API KeysAdd Google LoginAdd Microsoft Entra ID AuthenticationAdd Auth0 AuthenticationAdd Email VerificationCreate a Password Reset APIStore Secrets and API Keys SecurelyAdd Rate LimitingSecure CORS SettingsFastAPI Security Best Practices for ProductionFastAPI Authentication vs Authorization Explained

Async, Files and Real-Time

10

Background work, uploads, WebSockets and webhooks.

FastAPI Async and AwaitFastAPI Background Tasks TutorialSend Emails in the BackgroundUpload FilesUpload Multiple FilesDownload FilesServe Static FilesCreate a WebSocket Chat ApplicationAdd WebSocket AuthenticationCreate Webhooks

Questions people ask

Frequently asked questions

Is FastAPI good for beginners?

Yes, if you know basic Python functions and type hints. You can run a working endpoint in a few lines, and the automatic docs let you test it in your browser.

What is the difference between FastAPI and Flask?

Flask is a minimal WSGI framework where validation and API docs come from add-ons. FastAPI is an ASGI framework with validation, async support and interactive docs built in.

Which command installs FastAPI?

Run pip install "fastapi[standard]" inside a virtual environment. The standard extras include the fastapi command and Uvicorn.

Why does FastAPI return a 422 error?

A 422 means the request failed validation, such as a missing field or the wrong type. The response body names the field and explains the problem.

Do I have to use async def in FastAPI?

No. Use def for regular blocking code and async def when you await async libraries. FastAPI runs plain def routes in a thread pool.

Ready to build your first API?

Start with one endpoint, then add validation, a database and login one step at a time.