How to Create a FastAPI Backend

How to Create a FastAPI Backend

FastAPI is a modern, fast (high-performance), web framework for building APIs with Python based on standard Python type hints. It is designed to be easy to use and to provide automatic interactive API documentation. This tutorial will guide you through the steps to create a FastAPI backend from scratch.

Step 1: Installation

First, ensure you have Python 3.6 or later installed. Then, you can install FastAPI and an ASGI server, such as Uvicorn, using pip:

pip install fastapi uvicorn

Step 2: Creating Your First FastAPI App

Create a file named main.py and add the following code to define your first FastAPI application:

from fastapi import FastAPI

app = FastAPI()

@app.get("/")
async def read_root():
    return {"message": "Hello World"}

This code snippet imports FastAPI, creates an app instance, and defines a single route that returns a JSON response with a "Hello World" message.

Step 3: Running the Application

Run the application using Uvicorn:

uvicorn main:app --reload

Open your browser and go to http://127.0.0.1:8000 to see your API in action. You can also access the automatic interactive API documentation at http://127.0.0.1:8000/docs (Swagger UI) and http://127.0.0.1:8000/redoc (ReDoc)【6†source】【8†source】.

Step 4: Creating CRUD Operations

Next, let's create a simple CRUD (Create, Read, Update, Delete) application. Start by defining a model for your data using Pydantic:

from typing import List, Optional
from uuid import UUID, uuid4
from pydantic import BaseModel
from enum import Enum

class Gender(str, Enum):
    male = "male"
    female = "female"

class Role(str, Enum):
    admin = "admin"
    user = "user"

class User(BaseModel):
    id: Optional[UUID] = uuid4()
    first_name: str
    last_name: str
    gender: Gender
    roles: List[Role]

Now, create an in-memory database and endpoints to handle CRUD operations:

db: List[User] = [
    User(id=uuid4(), first_name="John", last_name="Doe", gender=Gender.male, roles=[Role.user]),
    User(id=uuid4(), first_name="Jane", last_name="Doe", gender=Gender.female, roles=[Role.user]),
]

@app.get("/users", response_model=List[User])
async def get_users():
    return db

@app.post("/users", response_model=User)
async def create_user(user: User):
    db.append(user)
    return user

@app.get("/users/{user_id}", response_model=User)
async def get_user(user_id: UUID):
    for user in db:
        if user.id == user_id:
            return user
    return {"error": "User not found"}

@app.delete("/users/{user_id}")
async def delete_user(user_id: UUID):
    for user in db:
        if user.id == user_id:
            db.remove(user)
            return {"message": "User deleted"}
    return {"error": "User not found"}

These endpoints allow you to create, read, and delete users from the in-memory database【7†source】【10†source】.

Step 5: Testing Your API

Use FastAPI's built-in testing client to create tests for your API. For example, to test the GET /users endpoint, you can use the following code:

from fastapi.testclient import TestClient

client = TestClient(app)

def test_get_users():
    response = client.get("/users")
    assert response.status_code == 200
    assert response.json() == db

This test checks that the GET /users endpoint returns a 200 status code and the correct data【9†source】.

Conclusion

You have now created a basic FastAPI backend with CRUD operations and tested it. FastAPI provides a lot of features out-of-the-box, including automatic API documentation and easy testing, making it a powerful tool for building APIs quickly and efficiently.

For more information and advanced usage, refer to the FastAPI documentation.

References

Leave a Comment

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