▶ Sign up free for the video, slides & prompts
The lesson below is open to all. Enter your email once to unlock every video, slide deck, prompt and code example on this device.
Checking…
Build an API with FastAPI
Turn your Python into a web service in minutes.
🎬 Video version coming soon — read it now
An API lets other programs, such as a website, mobile app or another team's service, use your Python code over the internet. FastAPI is the most popular modern framework for building Python APIs: fast, easy and built on the type hints you already know.
Install and write an API
main.py:
Run it
Open http://127.0.0.1:8000/courses in a browser. Then open http://127.0.0.1:8000/docs: FastAPI generated interactive documentation where you can try every endpoint.
What FastAPI does from your type hints
course_id: intin the path: "/courses/abc" gets an automatic 422 errorlevel: str | None = None: an optional query parameter, as in /courses?level=beginnercourse: CourseIn: the JSON body is parsed and validated with Pydantic. A 2-letter title is rejected with a clear message- Return a dict or list and it becomes JSON
HTTP basics in one minute
- GET reads data; POST creates; PUT/PATCH update; DELETE removes
- Status codes: 200 OK, 201 Created, 400 bad request, 404 not found, 422 validation error, 500 server error
Testing an API
The pytest skills from earlier apply directly.
Real data
The COURSES dictionary disappears when the server restarts. Real APIs store data in a database, such as SQLite to start with, or PostgreSQL in production. That's the natural next step after this course.
In one line
FastAPI turns type-hinted functions into a validated JSON API with automatic docs; use HTTPException for errors and TestClient for tests.
Share with a friend