FastAPI Project Setup and First Endpoint
Install FastAPI, create a project, and write your first GET endpoint.
FastAPI Project Setup and First Endpoint is a free Python Academy lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Python Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
What Is FastAPI?
FastAPI is a modern Python web framework for building REST APIs. It provides automatic OpenAPI docs, type-checked request/response models via Pydantic, and async-native performance.
# pip install fastapi uvicorn
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def root():
return {"message": "Hello, FastAPI"}Running the Server
Run with uvicorn. The --reload flag restarts automatically on code changes during development.
# main.py
from fastapi import FastAPI
app = FastAPI()
@app.get("/health")
def health(): return {"status": "ok"}
# Terminal:
# uvicorn main:app --reload
# → http://127.0.0.1:8000
# → http://127.0.0.1:8000/docs (Swagger UI)HTTP Methods
Decorate route functions with @app.get, @app.post, @app.put, @app.delete, or @app.patch.
from fastapi import FastAPI
app = FastAPI()
@app.get("/items")
def list_items(): return []
@app.post("/items")
def create_item(): return {"id": 1}
@app.delete("/items/{item_id}")
def delete_item(item_id: int): return {"deleted": item_id}Path Parameters
Declare path parameters in the route string with {name} and as function arguments with type annotations.
from fastapi import FastAPI
app = FastAPI()
@app.get("/users/{user_id}")
def get_user(user_id: int):
return {"user_id": user_id, "name": "Alice"}
# GET /users/42 → {"user_id": 42, "name": "Alice"}Query Parameters
Function parameters not in the path become query parameters.
from fastapi import FastAPI
app = FastAPI()
@app.get("/items")
def list_items(skip: int = 0, limit: int = 10, q: str | None = None):
return {"skip": skip, "limit": limit, "q": q}
# GET /items?skip=5&limit=20&q=searchPydantic Request Body
Use a Pydantic BaseModel as the parameter type to declare and validate a JSON request body.
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: str
price: float
in_stock: bool = True
@app.post("/items")
def create_item(item: Item):
return {"received": item.model_dump()}Pydantic Validation Errors
If the request body does not match the schema, FastAPI returns a 422 Unprocessable Entity with a detailed error message automatically.
# POST /items with body {"name": 123}
# → HTTP 422 Unprocessable Entity
# {
# "detail": [
# {
# "type": "string_type",
# "loc": ["body","name"],
# "msg": "Input should be a valid string"
# }
# ]
# }Response Models
Use response_model= to declare what the endpoint returns. FastAPI validates the response and filters out extra fields.
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class UserOut(BaseModel):
id: int
name: str
@app.get("/users/{uid}", response_model=UserOut)
def get_user(uid: int):
return {"id": uid, "name": "Alice", "password": "secret"} # password filtered outStatus Codes
Set the default success status code with status_code=. Import common codes from fastapi.status.
from fastapi import FastAPI, status
app = FastAPI()
@app.post("/items", status_code=status.HTTP_201_CREATED)
def create_item():
return {"id": 1}
# HTTP 201 Created is returned on successHTTPException
Raise HTTPException to return an error response with a custom status code and detail message.
from fastapi import FastAPI, HTTPException
app = FastAPI()
fake_db = {1: "Alice"}
@app.get("/users/{uid}")
def get_user(uid: int):
if uid not in fake_db:
raise HTTPException(status_code=404, detail="User not found")
return {"name": fake_db[uid]}Automatic Documentation
FastAPI generates Swagger UI at /docs and ReDoc at /redoc automatically from your route annotations.
# After starting with uvicorn:
# http://localhost:8000/docs — Swagger UI (try the API live)
# http://localhost:8000/redoc — ReDoc (clean docs view)
# http://localhost:8000/openapi.json — raw OpenAPI schemaQuick Check
How do you declare a required JSON request body parameter in FastAPI?
Recap
FastAPI routes are decorated functions: path params in the URL, query params as typed arguments, request bodies as Pydantic models. Raise HTTPException for errors. Swagger UI is auto-generated at /docs.
Frequently asked questions
Is the “FastAPI Project Setup and First Endpoint” lesson free?
Yes — the full text of “FastAPI Project Setup and First Endpoint” is free to read here on the web, and the Python Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Python Academy course, upgrade to CoddyKit PRO.
What will I learn in “FastAPI Project Setup and First Endpoint”?
Install FastAPI, create a project, and write your first GET endpoint. You practise Python Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Python Academy?
No prior experience is required. Python Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “FastAPI Project Setup and First Endpoint” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Python Academy lesson?
Yes. Every Python Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- FastAPI Project Setup and First Endpoint
- Path Parameters, Query Params, and Request Bodies
- Dependency Injection and Authentication
- Async Endpoints and Database Integration