Building APIs with FastAPI
FastAPI is a modern, high-performance web framework that builds typed APIs from ordinary Python type hints. You get automatic validation, interactive OpenAPI docs, async support, and dependency injection — with very little boilerplate.
Learn Building APIs with FastAPI in our free Python course — an interactive lesson with runnable examples, a practice exercise and a quick reference.
Part of the free Python course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
What You'll Learn in This Lesson
- • Creating a FastAPI() app and path operations
- • Path and query parameters driven by type hints
- • Pydantic models for request and response bodies
- • Automatic OpenAPI / Swagger docs at /docs
- • Async endpoints with async def
- • Dependency injection with Depends
- • Running the server with uvicorn
🚀 1. Your First API
▶️ 2. Running with uvicorn
FastAPI is an ASGI app; run it with the uvicorn server:
--reload restarts the server automatically when you edit code. Then open http://127.0.0.1:8000 .
🛣️ 3. Path and Query Parameters
Names in the path become path parameters; extra typed arguments become query parameters:
Parameter
Comes from
item_id
The URL path (in curly braces)
q
The query string (?q=...)
Because item_id is typed int , FastAPI rejects /items/abc with a clear error.
📦 4. Request Bodies with Pydantic
Type a parameter as a Pydantic model and FastAPI parses and validates the JSON body:
Send invalid JSON and FastAPI responds with a structured 422 error describing each problem.
📖 5. Automatic Docs
With the server running, visit these URLs in your browser:
URL
What you get
/docs
Interactive Swagger UI
/redoc
Clean ReDoc documentation
/openapi.json
The raw OpenAPI schema
You can try every endpoint right from /docs — no extra setup required.
⚡ 6. Async Endpoints
Use async def when an endpoint awaits I/O like a database or external API:
FastAPI supports both def and async def handlers; use async when you need to await something.
🔌 7. Dependency Injection
Depends() lets you share logic (auth, db sessions, common params) across endpoints:
FastAPI calls pagination , validates its parameters, and passes the result in as page .
🎉 Conclusion
✔ Validate path, query, and body data automatically
✔ Share logic cleanly with dependency injection
Type hints do double duty: they document and validate your API at once.
📋 Quick Reference — FastAPI
Syntax
What it does
app = FastAPI()
Create the application
Register a GET route
item: ItemModel
Validated request body
Depends(fn)
Dependency injection
uvicorn main:app --reload
Run the dev server
You can now build typed, documented, validated web APIs with FastAPI.
Up next: mypy — catch type bugs before your code ever runs.
Practice quiz
How do you create a FastAPI application instance?
- app = FastAPI()
- app = fastapi.create()
- app = App()
- app = Server()
Answer: app = FastAPI(). You import FastAPI and instantiate it: app = FastAPI(); this app object holds all your routes.
Which decorator registers a handler for HTTP GET on a path?
- @get('/')
- @app.route('/')
- @app.get('/')
- @app.handle('/')
Answer: @app.get('/'). FastAPI uses one decorator per method, e.g. @app.get('/') and @app.post('/items').
In @app.get('/items/{item_id}'), how is item_id passed to the function?
- It must be parsed manually
- As a path parameter argument
- As a global variable
- Through request.body
Answer: As a path parameter argument. Names in {curly braces} become path parameters; declare a same-named function argument with a type hint.
If a function parameter has a type hint but is NOT in the path, FastAPI treats it as a what?
- Path parameter
- Header
- Cookie
- Query parameter
Answer: Query parameter. Parameters not present in the path are interpreted as query string parameters (e.g. ?limit=10).
How does FastAPI validate and parse a JSON request body?
- With a Pydantic BaseModel type-hinted parameter
- With a regular dict argument
- With request.json() only
- It does not validate bodies
Answer: With a Pydantic BaseModel type-hinted parameter. Declare a parameter typed as a Pydantic BaseModel; FastAPI parses, validates, and injects the body.
Where are the automatic interactive Swagger UI docs served by default?
- /api/docs
- /docs
- /openapi
- /swagger
Answer: /docs. FastAPI auto-generates interactive Swagger UI at /docs (and ReDoc at /redoc) from your type hints.
What keyword lets an endpoint function use await for non-blocking I/O?
- yield
- defer
- parallel
- async
Answer: async. Declaring 'async def' makes the path operation a coroutine so you can await async calls without blocking.
Which function provides dependency injection in FastAPI?
- Provide()
- Require()
- Depends()
- Inject()
Answer: Depends(). Depends() declares a dependency; FastAPI resolves it and passes the result into your endpoint.
Which ASGI server is commonly used to run a FastAPI app in development?
- gunicorn-wsgi
- uvicorn
- flask run
- node
Answer: uvicorn. FastAPI is an ASGI app; uvicorn is the standard ASGI server, e.g. 'uvicorn main:app --reload'.
What open standard does FastAPI generate to describe your API automatically?
- OpenAPI
- RAML
- GraphQL schema
- WSDL
Answer: OpenAPI. FastAPI generates an OpenAPI schema from your routes and types, which powers the /docs and /redoc UIs.
Continue this course
- Previous: Data Visualization with Matplotlib
- Next: Static Type Checking with mypy