# Building REST APIs with FastAPI and Python
In the world of web development, REST APIs serve as the backbone for connecting frontend applications with backend services. FastAPI, a modern Python web framework, has quickly gained popularity for building robust, high-performance REST APIs. In this article, we’ll explore how to use FastAPI to create scalable APIs efficiently, highlighting its key features, advantages, and providing sample code snippets to get you started.
—
## Why Choose FastAPI?
FastAPI is a Python framework designed for building APIs with speed and simplicity. It stands out due to its:
– **Fast performance:** Built on Starlette and Pydantic, FastAPI is extremely fast, competing with frameworks like Node.js and Go.
– **Ease of use:** With automatic data validation, dependency injection, and minimal boilerplate code, developers can focus on business logic.
– **API documentation:** FastAPI automatically generates interactive Swagger UI and ReDoc documentation for your APIs.
– **Asynchronous programming:** FastAPI supports asynchronous code out of the box, making it ideal for applications requiring concurrency.
—
## Setting Up FastAPI
Before we dive into building APIs, let’s set up FastAPI in a Python environment.
### Prerequisites
– Python 3.7 or higher.
– A basic understanding of Python and REST APIs.
### Installation
Install FastAPI and Uvicorn (ASGI server) using pip:
“`bash
pip install fastapi uvicorn
“`
—
## Building a Simple REST API with FastAPI
Let’s build a basic API for managing a list of books.
### Step 1: Create the Project Directory
Start by creating a project directory:
“`bash
mkdir fastapi-books-api
cd fastapi-books-api
“`
### Step 2: Write Your First FastAPI Application
Create a file named `main.py` and write the following code:
“`python
from fastapi import FastAPI
app = FastAPI()
@app.get(“/”)
def read_root():
return {“message”: “Welcome to the Books API”}
@app.get(“/books”)
def get_books():
return [
{“id”: 1, “title”: “1984”, “author”: “George Orwell”},
{“id”: 2, “title”: “To Kill a Mockingbird”, “author”: “Harper Lee”}
]
“`
Here’s what the code does:
– **`FastAPI()`**: Creates an instance of the FastAPI application.
– **`@app.get(path)`**: Defines a route for HTTP GET requests. The `path` specifies the endpoint.
### Step 3: Run the Server
Run the application using Uvicorn:
“`bash
uvicorn main:app –reload
“`
Open your browser and navigate to `http://127.0.0.1:8000`. You’ll see the output from the root endpoint.
—
## Adding Routes for CRUD Operations
Let’s extend the API to include CRUD operations for managing books. Update your `main.py` file:
“`python
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
app = FastAPI()
# Define a Book model
class Book(BaseModel):
id: int
title: str
author: str
# In-memory database
books = []
@app.get(“/books”)
def get_books():
return books
@app.post(“/books”)
def create_book(book: Book):
books.append(book)
return book
@app.get(“/books/{book_id}”)
def get_book(book_id: int):
for book in books:
if book.id == book_id:
return book
raise HTTPException(status_code=404, detail=”Book not found”)
@app.put(“/books/{book_id}”)
def update_book(book_id: int, updated_book: Book):
for index, book in enumerate(books):
if book.id == book_id:
books[index] = updated_book
return updated_book
raise HTTPException(status_code=404, detail=”Book not found”)
@app.delete(“/books/{book_id}”)
def delete_book(book_id: int):
for index, book in enumerate(books):
if book.id == book_id:
books.pop(index)
return {“message”: “Book deleted successfully”}
raise HTTPException(status_code=404, detail=”Book not found”)
“`
### Explanation:
1. **`BaseModel`:** Used for data validation and serialization with Pydantic.
2. **CRUD operations:**
– `GET /books`: Retrieve all books.
– `POST /books`: Create a new book.
– `GET /books/{book_id}`: Retrieve a book by ID.
– `PUT /books/{book_id}`: Update an existing book.
– `DELETE /books/{book_id}`: Delete a book by ID.
3. **Error handling:** `HTTPException` is used to handle 404 errors when a book is not found.
—
## Interactive API Documentation
One of FastAPI’s standout features is its automatic API documentation. When the server is running, visit:
– **Swagger UI:** [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs)
– **ReDoc:** [http://127.0.0.1:8000/redoc](http://127.0.0.1:8000/redoc)
These interfaces allow you to interact with your API, view schema definitions, and test endpoints.
—
## Advanced Features: Dependency Injection and Middleware
### Dependency Injection
FastAPI allows you to inject dependencies into your endpoints. For example:
“`python
from fastapi import Depends
def common_query_parameters(skip: int = 0, limit: int = 10):
return {“skip”: skip, “limit”: limit
Jkoder.com Tutorials, Tips and interview questions for Java, J2EE, Android, Spring, Hibernate, Javascript and other languages for software developers