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

Minimal Application

app/main.py:

python
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/json automatically

Run With Uvicorn

From project root (parent of app/):

bash
uvicorn app.main:app --reload

Code explanation:

  • app.main — Python module path
  • app — variable name of the FastAPI instance
  • --reload — auto restart on code changes (development only)

Custom port:

bash
uvicorn app.main:app --reload --port 8080

Expected output includes:

text
Uvicorn running on http://127.0.0.1:8000

Test With curl and Browser

bash
curl http://127.0.0.1:8000/

Expected:

json
{"message":"Hello, FastAPI!"}

Open interactive docs:

text
http://127.0.0.1:8000/docs

Try GET / from Swagger UI—no extra Postman setup required.

Multiple Routes and Methods

Code explanation:

  • item_id: int converts and validates the path segment
  • POST with a simple parameter expects query or form by default—JSON bodies come in chapter 4

JSONResponse and Status Codes

python
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 None

Or explicit response:

python
@app.get("/custom")
def custom():
    return JSONResponse(
        status_code=200,
        content={"key": "value"},
        headers={"X-Custom": "demo"},
    )

App Metadata

python
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
  • /docs loads Swagger UI
  • curl succeeds 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.