FastAPI Tutorial for Beginners: Build Your First Python API

2 weeks ago 30
Club.noww.in

You’ve written some Python and now you want other programs to talk to it over the web. An API does exactly that, and it takes less code than most people expect.

Quick answer: this FastAPI tutorial for beginners builds a working order API in one file. Create a FastAPI() app, decorate plain functions with @app.get or @app.post, then start it with fastapi dev main.py.

from fastapi import FastAPI app = FastAPI(title="Order Tracking API") @app.get("/") def home(): return {"message": "Order Tracking API is running"}

We built and ran every step below on Python 3.12.5 and FastAPI 0.162.2, against a real local server. The running example is a small order tracker for a US online store.

What You Need Before You Start

  • Python 3.10 or newer, because the code uses the str | None type syntax.
  • Basic Python: functions, dictionaries and lists.

If you’ve never set up an environment, managing several Python versions covers the groundwork. An API here simply means URLs that return JSON instead of web pages.

Step 1: Install FastAPI in a Virtual Environment

Make a folder, create a virtual environment inside it and install FastAPI with its standard extras. The extras bring the fastapi command and the Uvicorn server:

mkdir order-api cd order-api python -m venv .venv .venv\Scripts\activate pip install "fastapi[standard]"

On macOS or Linux, activate with source .venv/bin/activate. If an import fails afterward, this ModuleNotFoundError fix usually explains why.

Step 2: Create and Run a FastAPI App

Save the code below as main.py. The app object is your API, and @app.get("/") tells FastAPI to call home() whenever someone requests the root URL. Whatever dictionary you return becomes JSON.

from fastapi import FastAPI app = FastAPI(title="Order Tracking API") @app.get("/") def home(): return {"message": "Order Tracking API is running"}

Output:

Server started at http://127.0.0.1:8000 Documentation at http://127.0.0.1:8000/docs INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) INFO: Application startup complete.
VS Code showing a FastAPI main.py file with the fastapi dev command running the server on port 8000 in the terminalfastapi dev starts the server and reloads it each time you save.

Open http://127.0.0.1:8000 in a browser and you’ll see the JSON:

Browser showing the JSON message returned by the FastAPI root endpoint at 127.0.0.1 port 8000The dictionary from home(), returned as JSON.

Weighing an API against other project types? Building apps with Python compares them.

Step 3: Add a GET Endpoint That Lists Orders

Same file, now with data. We’ll keep three orders in a plain list, since a database would only distract from the API itself:

ORDERS = [ {"id": 1001, "customer": "Megan Carter", "city": "Austin, TX", "total": 84.50, "status": "shipped"}, {"id": 1002, "customer": "Tyler Brooks", "city": "Denver, CO", "total": 129.99, "status": "processing"}, {"id": 1003, "customer": "Hannah Reed", "city": "Boston, MA", "total": 42.25, "status": "delivered"}, ] @app.get("/orders") def list_orders(status: str | None = None): if status: return [o for o in ORDERS if o["status"] == status] return ORDERS

Any function argument that isn’t in the URL path becomes a query parameter, so status is read from ?status=shipped. This script calls the running server with httpx, which the standard extras install:

import httpx BASE = "http://127.0.0.1:8000" orders = httpx.get(f"{BASE}/orders").json() print(len(orders), "orders") for order in orders: print(order["id"], order["customer"], order["status"]) shipped = httpx.get(f"{BASE}/orders", params={"status": "shipped"}) print(shipped.url) print(shipped.json())

Output:

3 orders 1001 Megan Carter shipped 1002 Tyler Brooks processing 1003 Hannah Reed delivered http://127.0.0.1:8000/orders?status=shipped [{'id': 1001, 'customer': 'Megan Carter', 'city': 'Austin, TX', 'total': 84.5, 'status': 'shipped'}]
Command Prompt output listing three US orders from a FastAPI endpoint and filtering them with a status query parameterAll three orders, then only the shipped one.

That returns 3 orders, and the filter narrows them to Megan Carter’s $84.50 order. The filter itself is a compact Python for loop.

Step 4: Get One Order by ID

Curly braces in the route create a path parameter. The int type hint isn’t decoration: FastAPI converts the URL text to an integer and rejects anything else. Add HTTPException to your import, then this route:

@app.get("/orders/{order_id}") def get_order(order_id: int): for order in ORDERS: if order["id"] == order_id: return order raise HTTPException(status_code=404, detail="Order not found") import httpx BASE = "http://127.0.0.1:8000" for path in ("/orders/1002", "/orders/9999", "/orders/abc"): response = httpx.get(BASE + path) print(path, "->", response.status_code) print(response.json())

Output:

/orders/1002 -> 200 {'id': 1002, 'customer': 'Tyler Brooks', 'city': 'Denver, CO', 'total': 129.99, 'status': 'processing'} /orders/9999 -> 404 {'detail': 'Order not found'} /orders/abc -> 422 {'detail': [{'type': 'int_parsing', 'loc': ['path', 'order_id'], 'msg': 'Input should be a valid integer, unable to parse string as an integer', 'input': 'abc'}]}
Command Prompt output of a FastAPI get by id endpoint returning 200, a 404 not found error and a 422 validation errorOne URL pattern, three outcomes: 200, 404 and 422.

Order 1002 comes back with a 200, 9999 gets our 404, and abc gets a 422 that we never had to code. Type hints drive all of this; checking variable types in Python is a useful refresher.

Step 5: Accept New Orders With POST and Pydantic

A Pydantic model is a class describing the JSON you’ll accept. Fields without a default are required, and Field(gt=0) rejects a zero or negative total. Here’s the complete main.py with those changes. I dropped the Step 2 home route because this API doesn’t need it:

from fastapi import FastAPI, HTTPException from pydantic import BaseModel, Field app = FastAPI(title="Order Tracking API") ORDERS = [ {"id": 1001, "customer": "Megan Carter", "city": "Austin, TX", "total": 84.50, "status": "shipped"}, {"id": 1002, "customer": "Tyler Brooks", "city": "Denver, CO", "total": 129.99, "status": "processing"}, {"id": 1003, "customer": "Hannah Reed", "city": "Boston, MA", "total": 42.25, "status": "delivered"}, ] class NewOrder(BaseModel): customer: str = Field(examples=["Jordan Hayes"]) city: str = Field(examples=["Seattle, WA"]) total: float = Field(gt=0, examples=[59.75]) @app.get("/orders") def list_orders(status: str | None = None): if status: return [o for o in ORDERS if o["status"] == status] return ORDERS @app.get("/orders/{order_id}") def get_order(order_id: int): for order in ORDERS: if order["id"] == order_id: return order raise HTTPException(status_code=404, detail="Order not found") @app.post("/orders", status_code=201) def create_order(new_order: NewOrder): order = new_order.model_dump() order["id"] = max(o["id"] for o in ORDERS) + 1 order["status"] = "processing" ORDERS.append(order) return order
VS Code showing the FastAPI main.py with a Pydantic NewOrder model and the POST orders route, with the server runningThe finished one-file API, with the server still running.

Because create_order takes a NewOrder argument, FastAPI reads the request body as JSON, validates it and hands you a typed object. Let’s send one good order and two bad ones:

import httpx BASE = "http://127.0.0.1:8000" good = {"customer": "Jordan Hayes", "city": "Seattle, WA", "total": 59.75} no_city = {"customer": "Ava Nguyen", "total": 18.40} bad_total = {"customer": "Ava Nguyen", "city": "Tampa, FL", "total": -5} for body in (good, no_city, bad_total): response = httpx.post(f"{BASE}/orders", json=body) print(response.status_code, response.json()) print(len(httpx.get(f"{BASE}/orders").json()), "orders now")

Output:

201 {'customer': 'Jordan Hayes', 'city': 'Seattle, WA', 'total': 59.75, 'id': 1004, 'status': 'processing'} 422 {'detail': [{'type': 'missing', 'loc': ['body', 'city'], 'msg': 'Field required', 'input': {'customer': 'Ava Nguyen', 'total': 18.4}}]} 422 {'detail': [{'type': 'greater_than', 'loc': ['body', 'total'], 'msg': 'Input should be greater than 0', 'input': -5, 'ctx': {'gt': 0.0}}]} 4 orders now
Command Prompt output of a FastAPI POST request returning 201 for a valid order and 422 errors for a missing city and a negative totalThe valid order gets id 1004. Neither bad order reaches our function.

Only Jordan Hayes’s $59.75 order was saved, so the list now holds 4, since lists are mutable. The loc value in each error names the exact field that failed.

Step 6: Test the API in Swagger UI at /docs

FastAPI writes interactive documentation for you. With the server running, open http://127.0.0.1:8000/docs to see every endpoint:

Swagger UI at the FastAPI docs URL listing the list orders, get order and create order endpointsEach route appears automatically, with no extra code.

Click POST /orders, then Try it out. The request body is already filled in from the examples we gave each field:

Swagger UI POST orders panel in Try it out mode with a sample JSON request body for a Seattle customerThe sample body comes straight from the Pydantic model.

Click Execute. Swagger sends a real request and shows the response underneath:

Swagger UI showing a 201 response with the new order after executing the FastAPI POST requestStatus 201 and the saved order, id included.

The same steps work for GET /orders/{order_id}. Type 1001 in the box and click Execute:

Swagger UI showing the JSON for order 1001 returned by the FastAPI get order by id endpointOrder 1001, fetched from the browser without writing a client.

FastAPI Cheat Sheet: What We Tested

RequestWhat it doesResult
GET /orders?status=shippedFilters by query parameter200, 1 order
GET /orders/9999Unknown id404
GET /orders/abcWrong type in the path422
POST /orders, valid JSONSaves the order201, id 1004
POST /orders, bad JSONFails validation422

Common FastAPI Mistakes to Avoid

  • Installing plain fastapi. The command then stops and asks you to install fastapi[standard].
  • Expecting saved data to survive. Our list lives in memory, and after a restart we were back to 3 orders.
  • Treating a 422 as a server bug. It means the client sent bad data; read detail to see which field.

Once the API works, pin your package versions so it keeps working.

Is FastAPI Good for Beginners?

We think so. You write ordinary functions with type hints, and validation and docs come free. Flask asks for less up front, but you’d add validation and documentation yourself.

Next Steps After Your First API

Swap the list for a database when you’re ready, and keep secrets out of your code with environment variables. To see FastAPI serving something heavier, try deploying a machine learning model with FastAPI and Docker.

These are the pages we’d open next:

Frequently asked questions

How long does it take to learn FastAPI?

If you know basic Python, you can build the API in this tutorial in under an hour. Databases and authentication take longer.

Do I need async def in FastAPI?

No. A plain def route works, and FastAPI runs it in a thread pool. Use async def when the code inside awaits something.

What’s the difference between fastapi dev and fastapi run?

fastapi dev is for development and reloads on every save. fastapi run is the production command.

Why does FastAPI return a 422 error?

The request didn’t match your type hints or Pydantic model. The detail list in the response names each failing field.

Where can I find the official FastAPI docs?

The FastAPI First Steps tutorial is the official starting point and is kept current with each release.

Read Entire Article