FastAPI Tutorial for Beginners: Python Web API Development

FastAPI Tutorial for Beginners: Python Web API Development

FastAPI is a modern, high-performance web framework for building APIs with Python 3.7+ based on standard Python type hints. It’s designed to be fast, easy to use, and highly productive. This tutorial will guide you through the fundamentals of FastAPI, from setting up your first project to building complex APIs with advanced features.

Why FastAPI?

FastAPI offers several advantages over other Python web frameworks:

  • High Performance: Built on top of Starlette and Pydantic, FastAPI boasts performance comparable to NodeJS and Go, making it one of the fastest Python web frameworks available.
  • Automatic Documentation: FastAPI automatically generates interactive API documentation using Swagger UI and ReDoc, simplifying testing and client integration.
  • Type Hinting and Validation: Leveraging Python’s type hints, FastAPI provides automatic data validation and conversion, reducing errors and boilerplate code.
  • Easy to Learn: Its intuitive syntax and minimal setup make it easy to learn and use, even for beginners.
  • Asynchronous Support: Built-in support for asynchronous programming with async/await syntax allows for highly concurrent applications.
  • Dependency Injection: A powerful dependency injection system promotes modularity and testability.

Setting up Your Environment:

  1. Install Python: Ensure you have Python 3.7 or higher installed. You can download it from the official Python website.

  2. Create a Virtual Environment (Recommended): Create a virtual environment to isolate your project dependencies.

bash
python3 -m venv .venv

  1. Activate the Virtual Environment:

“`bash
# Linux/macOS
source .venv/bin/activate

# Windows
.venv\Scripts\activate
“`

  1. Install FastAPI and Uvicorn:

bash
pip install fastapi uvicorn[standard]

Creating Your First FastAPI Application:

  1. Create a file named main.py:

“`python
from fastapi import FastAPI

app = FastAPI()

@app.get(“/”)
async def root():
return {“message”: “Hello World”}
“`

  1. Run the Application:

bash
uvicorn main:app --reload

This command starts the Uvicorn ASGI server, hosting your FastAPI application. The --reload flag enables automatic reloading of the server on code changes.

  1. Access the API: Open your web browser and navigate to http://127.0.0.1:8000/. You should see the JSON response {"message": "Hello World"}. You can also access the automatic documentation at http://127.0.0.1:8000/docs (Swagger UI) and http://127.0.0.1:8000/redoc (ReDoc).

Path Parameters:

You can define path parameters to capture dynamic values within the URL.

“`python
from fastapi import FastAPI, Path

app = FastAPI()

@app.get(“/items/{item_id}”)
async def read_item(item_id: int = Path(…, title=”The ID of the item to get”)):
return {“item_id”: item_id}
“`

The Path function allows you to declare path parameters and add metadata like title and description for the documentation. The ellipsis ... makes the parameter required.

Query Parameters:

Query parameters allow you to pass optional parameters in the URL after a question mark.

“`python
from fastapi import FastAPI, Query

app = FastAPI()

@app.get(“/items/”)
async def read_items(q: str | None = Query(default=None, max_length=50)):
results = {“items”: [{“item_id”: “Foo”}, {“item_id”: “Bar”}]}
if q:
results.update({“q”: q})
return results
“`

Request Body:

For more complex data, you can use request bodies with Pydantic models.

“`python
from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class Item(BaseModel):
name: str
description: str | None = None
price: float
tax: float | None = None

@app.post(“/items/”)
async def create_item(item: Item):
return item
“`

Data Validation:

Pydantic provides automatic data validation based on the type hints. For example, if you send a request to the /items/ endpoint with an invalid price (e.g., a string instead of a float), FastAPI will return a 422 Unprocessable Entity error.

Dependency Injection:

FastAPI’s dependency injection system helps manage dependencies and promotes code reusability.

“`python
from fastapi import Depends, FastAPI

app = FastAPI()

async def common_parameters(q: str | None = None, skip: int = 0, limit: int = 100):
return {“q”: q, “skip”: skip, “limit”: limit}

@app.get(“/items/”)
async def read_items(commons: dict = Depends(common_parameters)):
return commons
“`

Asynchronous Programming:

FastAPI supports asynchronous programming using async and await.

“`python
import asyncio
from fastapi import FastAPI

app = FastAPI()

@app.get(“/sleep”)
async def slow_endpoint():
await asyncio.sleep(1) # Simulate a long-running task
return {“message”: “Slept for 1 second”}
“`

Error Handling:

You can handle errors gracefully using the HTTPException class.

“`python
from fastapi import FastAPI, HTTPException

app = FastAPI()

@app.get(“/items/{item_id}”)
async def read_item(item_id: int):
if item_id == 3:
raise HTTPException(status_code=404, detail=”Item not found”)
return {“item_id”: item_id}
“`

Middleware:

Middleware allows you to add functionality that runs before or after a request is processed.

“`python
from fastapi import FastAPI, Request
from starlette.middleware.base import BaseHTTPMiddleware

class TimingMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request: Request, call_next):
import time
start_time = time.time()
response = await call_next(request)
process_time = time.time() – start_time
response.headers[“X-Process-Time”] = str(process_time)
return response

app = FastAPI()
app.add_middleware(TimingMiddleware)

@app.get(“/”)
async def root():
return {“message”: “Hello World”}
“`

Testing:

Testing your API is crucial for ensuring its correctness and reliability. You can use pytest along with requests or httpx for testing.

“`python
import pytest
from starlette.testclient import TestClient

from main import app # Replace main with your main file

@pytest.fixture(scope=”module”)
def client():
with TestClient(app) as c:
yield c

def test_root(client: TestClient):
response = client.get(“/”)
assert response.status_code == 200
assert response.json() == {“message”: “Hello World”}

“`

This comprehensive tutorial provides a solid foundation for building APIs with FastAPI. By leveraging its powerful features, you can create high-performance, robust, and well-documented APIs with ease. Explore the official FastAPI documentation for more advanced topics and examples. Remember to leverage the community resources and forums for further assistance and knowledge sharing. As you progress, consider exploring advanced concepts such as database integration with ORMs, security implementations, and deployment strategies to build production-ready applications. Happy coding!

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top