Your First FastAPI Application
Introduction
A FastAPI app can be ten lines: create the app, register a route, return JSON. This chapter builds Hello FastAPI, runs it with Uvicorn, explores HTTP methods, opens Swagger UI, and returns custom status codes.
Prerequisites
- FastAPI Environment and Installation
- Virtual environment activated with FastAPI installed
Minimal Application
app/main.py:
from fastapi import FastAPI
app = FastAPI(title="Hello API", version="0.1.0")
@app.get("/")
def read_root():
return {"message": "Hello, FastAPI!"}app/__init__.py can be empty—it marks app as a package.
Code explanation:
FastAPI()creates the application object Uvicorn serves- Returning a dict produces
application/jsonautomatically
Run With Uvicorn
From project root (parent of app/):
uvicorn app.main:app --reloadCode explanation:
app.main— Python module pathapp— variable name of the FastAPI instance--reload— auto restart on code changes (development only)
Custom port:
uvicorn app.main:app --reload --port 8080Expected output includes:
Uvicorn running on http://127.0.0.1:8000Test With curl and Browser
curl http://127.0.0.1:8000/Expected:
{"message":"Hello, FastAPI!"}Open interactive docs:
http://127.0.0.1:8000/docsTry GET / from Swagger UI—no extra Postman setup required.
Multiple Routes and Methods
Code explanation:
item_id: intconverts and validates the path segmentPOSTwith a simple parameter expects query or form by default—JSON bodies come in chapter 4
JSONResponse and Status Codes
from fastapi import FastAPI
from fastapi.responses import JSONResponse
app = FastAPI()
@app.post("/items", status_code=201)
def create_item():
return {"id": 1, "name": "widget"}
@app.delete("/items/1", status_code=204)
def delete_item():
return NoneOr explicit response:
@app.get("/custom")
def custom():
return JSONResponse(
status_code=200,
content={"key": "value"},
headers={"X-Custom": "demo"},
)App Metadata
app = FastAPI(
title="My API",
description="Learning FastAPI on Hello Code",
version="1.0.0",
)Shows in /docs and /openapi.json.
Warning
--reload Is Not for Production
Reload spawns a watcher process—use plain Uvicorn or Gunicorn workers in production.
Practice Checklist
-
/returns JSON -
/docsloads Swagger UI -
curlsucceeds on port 8000 - You can stop the server with Ctrl+C
FAQ
Error: Could not import module "app.main"?
Run uvicorn from the directory that contains the app/ package, or set PYTHONPATH.
Address already in use?
Another process on port 8000—use --port 8001 or stop the old process.
Empty response on 204 DELETE?
204 No Content has no body—expected behavior.
Run from main.py directly?
Possible with uvicorn.run in if __name__—CLI style is more common.
Difference from Flask?
Flask uses flask run and WSGI; FastAPI uses Uvicorn and ASGI—see Flask first app.
Changes not appearing?
Ensure --reload is on or restart manually.