FastAPI Tutorial: Build a Python API in Easy Steps
FastAPI is a modern Python framework for building APIs. It validates data automatically and even generates interactive API documentation for you.
By Learn Refill Mentors · Updated
Why learn FastAPI?
- One of the fastest Python frameworks
- Automatic data validation with Pydantic
- Free interactive API docs at /docs
1Install FastAPI
Install FastAPI with its standard extras, which include the development server.
pip install "fastapi[standard]"2Create your first API
Save this as main.py.
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def home():
return {"message": "API is running"}3Run it and open the docs
Start the server, then open http://127.0.0.1:8000/docs to test your API in the browser.
fastapi dev main.py4Path and query parameters
Type hints tell FastAPI how to read and validate values.
@app.get("/courses/{course_id}")
def get_course(course_id: int, details: bool = False):
return {"id": course_id, "details": details}5Validate request data with Pydantic
Define the shape of incoming data. Invalid requests get a clear error automatically.
from pydantic import BaseModel, EmailStr
class Enquiry(BaseModel):
name: str
email: EmailStr
course: str
@app.post("/enquiries", status_code=201)
def create_enquiry(data: Enquiry):
return dataCommon mistakes
- Skipping type hints — FastAPI needs them for validation
- Putting every route in main.py instead of using routers
Practice task
Build a small expense API with endpoints to add an expense and list all expenses, and test it in /docs.
Frequently asked questions
FastAPI or Django?
FastAPI is lightweight and ideal for APIs. Django is a bigger all-in-one framework. We focus on FastAPI for modern API development.