Mathew K Analytics

Lesson 1 · FastAPI deep dive

FastAPI Tutorial #1: Getting Started — Build Your First Python API

On building real, production-shaped APIs with FastAPI. The FastAPI app, path operations, uvicorn, and the automatic interactive docs. Let's get into it.…

⬇ Download notebook🧠 Quiz & exercises

What you'll learn

Data

No separate download needed — the notebook creates or downloads everything it uses.

📓 Full notebook

Download .ipynb

FastAPI Deep-Dive, Video 1: Getting Started#

  • Video one of an eighteen-part series on building real, production-shaped APIs with FastAPI.
  • The FastAPI app, path operations, uvicorn, and the automatic interactive docs.
  • Let's get into it.

Part 1: What FastAPI Is and Why#

import fastapi
print(fastapi.__version__)
0.124.4

Part 2: Creating the App#

from fastapi import FastAPI
app = FastAPI(title='Demo API', version='1.0.0')
print(app.title, app.version)
Demo API 1.0.0

Part 3: The First Path Operation#

@app.get('/')
def read_root():
    return {'message': 'welcome to the demo API'}
print(read_root())
{'message': 'welcome to the demo API'}

Part 4: TestClient - Calling Endpoints Without a Live Server#

from fastapi.testclient import TestClient
client = TestClient(app)
response = client.get('/')
print(response.status_code)
print(response.json())
200
{'message': 'welcome to the demo API'}

Part 5: Multiple Path Operations and HTTP Methods#

@app.get('/status')
def get_status():
    return {'status': 'ok'}
@app.post('/echo')
def echo(payload: dict):
    return {'you_sent': payload}
print(client.get('/status').json())
print(client.post('/echo', json={'a': 1}).json())
{'status': 'ok'}
{'you_sent': {'a': 1}}

Part 6: Route Order Matters#

@app.get('/users/me')
def get_current_user():
    return {'user': 'current_user_placeholder'}
@app.get('/users/{user_id}')
def get_user(user_id: str):
    return {'user_id': user_id}
print(client.get('/users/me').json())
print(client.get('/users/42').json())
{'user': 'current_user_placeholder'}
{'user_id': '42'}

Part 7: Returning Lists and Nested Data#

@app.get('/items')
def list_items():
    return [{'id': 1, 'name': 'apple'}, {'id': 2, 'name': 'banana'}]
response = client.get('/items')
print(response.status_code)
print(response.json())
200
[{'id': 1, 'name': 'apple'}, {'id': 2, 'name': 'banana'}]

Part 8: Setting an Explicit Status Code#

from fastapi import status
@app.post('/items', status_code=status.HTTP_201_CREATED)
def create_item(payload: dict):
    return {'created': payload}
response = client.post('/items', json={'name': 'cherry'})
print(response.status_code)
201

Part 9: The Automatic Interactive Docs#

schema = app.openapi()
print(schema['info']['title'], schema['info']['version'])
print(sorted(schema['paths'].keys()))
Demo API 1.0.0
['/', '/echo', '/items', '/status', '/users/me', '/users/{user_id}']

Part 10: A Real Pattern - a Small Health Check and Info API#

info_app = FastAPI(title='Service Info API')
@info_app.get('/health')
def health_check():
    return {'status': 'healthy'}
@info_app.get('/info')
def service_info():
    return {'name': 'demo-service', 'version': '0.1.0'}
info_client = TestClient(info_app)
print(info_client.get('/health').json())
print(info_client.get('/info').json())
{'status': 'healthy'}
{'name': 'demo-service', 'version': '0.1.0'}

Wrap-Up: What You Learned#

  • FastAPI uses ordinary Python type hints to drive validation, data conversion, and documentation automatically.
  • A FastAPI application starts as a single FastAPI() instance that every route and setting attaches to.
  • A path operation combines an HTTP method decorator with a URL path and a plain Python function.
  • TestClient calls endpoints in-process, without starting a live server, the fast way to exercise an API.
  • @app.get, @app.post, @app.put, and @app.delete map to the corresponding HTTP methods.
  • Routes are matched in declaration order; fixed paths must be declared before conflicting parameterized ones.
  • A path operation can return any JSON-serializable structure: dicts, lists, and nested combinations.
  • status_code overrides the default 200 response code, e.g. 201 Created for a creation endpoint.
  • Every app generates a live OpenAPI schema automatically, powering the interactive docs at /docs and /redoc.
  • That wraps up getting started. Next up: Path and Query Parameters.

🧠 Test yourself

Pick an answer to check it. Your best score is saved in this browser.

  1. What does TestClient(app) let you do?

  2. A request goes to /users/me. Which function runs?

    @app.get('/users/{user_id}')
    def get_user(user_id: str):
        return {'user_id': user_id}
    
    @app.get('/users/me')
    def get_me():
        return {'user': 'me'}
    
  3. How do you make a POST endpoint answer with 201 Created?

  4. Where do the automatic interactive API docs live by default?

  5. What does this print?

    from fastapi import FastAPI
    from fastapi.testclient import TestClient
    
    app = FastAPI()
    
    @app.get('/')
    def root():
        return {'ok': True}
    
    client = TestClient(app)
    print(client.get('/').json(), client.get('/nope').status_code)
    

💻 Practice exercises

Try each one in the notebook or in your own editor before opening the solution.

  1. Create an app with GET /hello that returns {'message': 'hello'}, call it with TestClient, and print the status code and JSON.

    💡 Hint

    Use @app.get('/hello') and client.get('/hello').

    ✅ Show solution
    from fastapi import FastAPI
    from fastapi.testclient import TestClient
    
    app = FastAPI()
    
    @app.get("/hello")
    def hello():
        return {"message": "hello"}
    
    client = TestClient(app)
    response = client.get("/hello")
    print(response.status_code, response.json())
    assert response.json() == {"message": "hello"}
    
  2. Add GET /items/{item_id} with item_id typed as int and an optional query parameter 'q'. Test a valid request, then confirm that /items/abc returns 422.

    💡 Hint

    Declare item_id: int and q: str | None = None; FastAPI validates automatically.

    ✅ Show solution
    from fastapi import FastAPI
    from fastapi.testclient import TestClient
    
    app = FastAPI()
    
    @app.get("/items/{item_id}")
    def read_item(item_id: int, q: str | None = None):
        return {"item_id": item_id, "q": q}
    
    client = TestClient(app)
    print(client.get("/items/5?q=mug").json())
    assert client.get("/items/5").json() == {"item_id": 5, "q": None}
    print(client.get("/items/abc").status_code)
    assert client.get("/items/abc").status_code == 422
    
  3. Build a tiny items API: POST /items (status 201) stores a dict in a list, GET /items returns the list, and GET /items/count is declared before GET /items/{item_id}. Test it all with TestClient.

    💡 Hint

    Declare /items/count before the parameterized route and use status_code=201 on the POST.

    ✅ Show solution
    from fastapi import FastAPI, HTTPException, status
    from fastapi.testclient import TestClient
    
    app = FastAPI()
    ITEMS = []
    
    @app.post("/items", status_code=status.HTTP_201_CREATED)
    def create_item(payload: dict):
        ITEMS.append(payload)
        return {"created": payload}
    
    @app.get("/items")
    def list_items():
        return ITEMS
    
    @app.get("/items/count")          # fixed path first
    def count_items():
        return {"count": len(ITEMS)}
    
    @app.get("/items/{item_id}")
    def get_item(item_id: int):
        if item_id >= len(ITEMS):
            raise HTTPException(status_code=404, detail="not found")
        return ITEMS[item_id]
    
    client = TestClient(app)
    r = client.post("/items", json={"name": "apple"})
    print(r.status_code)
    assert r.status_code == 201
    client.post("/items", json={"name": "banana"})
    assert client.get("/items").json() == [{"name": "apple"}, {"name": "banana"}]
    assert client.get("/items/count").json() == {"count": 2}
    assert client.get("/items/1").json() == {"name": "banana"}
    assert client.get("/items/9").status_code == 404
    print("all good")
    

Found this useful?

All lessons, notebooks and datasets here are free. If they helped you, a coffee keeps new lessons coming.