โšก FastAPI Quick Start Guide

Build Your First API in 5 Minutes!

1

Install FastAPI & Uvicorn

First, install FastAPI (the framework) and Uvicorn (the server that runs it).

$ pip install fastapi uvicorn $ pip install python-multipart # For form data

๐Ÿ’ก Pro Tip

Create a virtual environment first to keep your project dependencies isolated:

$ python -m venv venv $ source venv/bin/activate # On Windows: venv\Scripts\activate $ pip install fastapi uvicorn
2

Create Your First API

Create a file called main.py with this code:

main.py # Import FastAPI from fastapi import FastAPI # Create FastAPI instance app = FastAPI() # Create your first endpoint @app.get("/") async def root(): return {"message": "Hello World"} # Another endpoint with a path parameter @app.get("/items/{item_id}") async def read_item(item_id: int): return {"item_id": item_id}

โœ… That's It!

You just created a fully functional API with automatic documentation in less than 15 lines of code!

3

Run Your API Server

Start the server using Uvicorn:

$ uvicorn main:app --reload INFO: Uvicorn running on http://127.0.0.1:8000 INFO: Application startup complete.

What does --reload do?

--reload automatically restarts the server when you change code. Perfect for development! Remove it in production.

4

Test Your API - 3 Ways!

Method 1: Interactive Docs (Recommended!)

FastAPI automatically generates beautiful interactive documentation!

Open your browser and visit:
๐Ÿ“– http://127.0.0.1:8000/docs (Swagger UI - Interactive)
๐Ÿ“‹ http://127.0.0.1:8000/redoc (ReDoc - Clean documentation)
๐Ÿ–ผ๏ธ At /docs you'll see:
โ€ข All your endpoints listed
โ€ข Try it out buttons to test each endpoint
โ€ข Automatic request/response examples
โ€ข Schema definitions

Method 2: Browser

Visit: http://127.0.0.1:8000/
You'll see: {"message": "Hello World"}

Method 3: Curl (Command Line)

$ curl http://127.0.0.1:8000/ {"message": "Hello World"} $ curl http://127.0.0.1:8000/items/42 {"item_id": 42}
5

Add Data Validation with Pydantic

Pydantic models automatically validate incoming data:

main.py from fastapi import FastAPI from pydantic import BaseModel from typing import Optional app = FastAPI() # Define data model class Item(BaseModel): name: str description: Optional[str] = None price: float tax: Optional[float] = None # POST endpoint with validation @app.post("/items/") async def create_item(item: Item): return { "name": item.name, "price": item.price, "total": item.price + (item.tax or 0) }

โœ… Automatic Validation!

FastAPI will automatically:

  • โœ“ Validate that name is a string
  • โœ“ Validate that price is a number
  • โœ“ Return 422 error if validation fails
  • โœ“ Generate JSON schema in docs
6

Use All HTTP Methods

main.py from fastapi import FastAPI, HTTPException app = FastAPI() # Fake database items = {} # GET - Read item @app.get("/items/{item_id}") async def read_item(item_id: int): if item_id not in items: raise HTTPException(status_code=404, detail="Item not found") return items[item_id] # POST - Create item @app.post("/items/") async def create_item(item: Item): item_id = len(items) + 1 items[item_id] = item return {"id": item_id, "item": item} # PUT - Update item @app.put("/items/{item_id}") async def update_item(item_id: int, item: Item): if item_id not in items: raise HTTPException(status_code=404, detail="Item not found") items[item_id] = item return {"updated": True, "item": item} # DELETE - Remove item @app.delete("/items/{item_id}") async def delete_item(item_id: int): if item_id not in items: raise HTTPException(status_code=404, detail="Item not found") del items[item_id] return {"deleted": True}

๐Ÿš€ Why FastAPI is Amazing

โšก
Blazing Fast

One of the fastest Python frameworks. Performance comparable to Node.js and Go.

๐Ÿ“–
Auto Documentation

Interactive API docs generated automatically. Test endpoints directly in your browser!

โœ…
Auto Validation

Pydantic validates all inputs automatically. Catch errors before they happen.

๐ŸŽฏ
Type Hints

Use Python type hints for better IDE support, auto-completion, and fewer bugs.

๐Ÿ”’
Security

Built-in support for OAuth2, JWT, API keys, and more authentication methods.

๐Ÿงช
Easy Testing

Simple to test with pytest. TestClient makes API testing straightforward.

7

Common FastAPI Patterns

Query Parameters

@app.get("/items/") async def read_items(skip: int = 0, limit: int = 10): return items[skip : skip + limit] # Usage: GET /items/?skip=0&limit=10

Path + Query Parameters

@app.get("/users/{user_id}/items") async def read_user_items( user_id: int, skip: int = 0, limit: int = 10 ): return {"user_id": user_id, "items": items[skip:skip+limit]} # Usage: GET /users/42/items?skip=0&limit=5

Status Codes

from fastapi import status @app.post("/items/", status_code=status.HTTP_201_CREATED) async def create_item(item: Item): return item @app.delete("/items/{item_id}", status_code=status.HTTP_204_NO_CONTENT) async def delete_item(item_id: int): # Returns 204 with no content pass

Response Models

class UserIn(BaseModel): username: str password: str # Never return this! class UserOut(BaseModel): username: str # Only return safe fields @app.post("/users/", response_model=UserOut) async def create_user(user: UserIn): # Password won't be in response! return user

FastAPI vs Flask vs Django

Feature FastAPI Flask Django
Performance โšกโšกโšก Extremely Fast โšกโšก Moderate โšก Slower
Auto Docs โœ… Built-in (Swagger/ReDoc) โŒ Manual โŒ Manual
Data Validation โœ… Automatic (Pydantic) โŒ Manual โœ… With DRF
Async Support โœ… Native โš ๏ธ Limited โœ… Added in 3.1+
Learning Curve Easy Easy Steep
Best For APIs, ML models, microservices Simple web apps Full web applications

โš ๏ธ Common Issues & Solutions

Issue: "Address already in use"

โžœ Another app is using port 8000. Use: uvicorn main:app --port 8001

Issue: Changes not showing up

โžœ Make sure you're using --reload flag

Issue: Import errors

โžœ Check your virtual environment is activated and packages are installed

Issue: 404 Not Found on /docs

โžœ Make sure server is running on correct port (check terminal output)

๐ŸŽฏ Next Steps: Level Up Your API

๐Ÿ“š Learn More