Building a RESTful API with FastAPI and Python: Step-by-Step Tutorial
Learn how to create a simple RESTful API using FastAPI and Python. This step-by-step tutorial is perfect for beginners who want to build efficient APIs quickly.
APIs (Application Programming Interfaces) are essential for modern web and mobile applications. A RESTful API allows different software systems to communicate over HTTP. FastAPI is a modern, fast, and easy-to-use Python web framework for building APIs. In this tutorial, you will learn how to build a basic RESTful API with FastAPI from scratch.
### Step 1: Install FastAPI and Uvicorn First, you need to install FastAPI and a server called Uvicorn to run your API. You can install them using pip:
pip install fastapi uvicorn### Step 2: Create Your First FastAPI Application Create a new Python file called `main.py`. This file will contain your API code. Start by importing FastAPI and creating an app instance.
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"message": "Hello, FastAPI!"}This code creates a simple API with one endpoint (`/`). When you visit this endpoint, it returns a JSON response with the message `Hello, FastAPI!`.
### Step 3: Run Your API Server To run the API server, use Uvicorn from the terminal:
uvicorn main:app --reloadThe `--reload` flag automatically reloads the server when you make code changes, which is handy during development. Open your browser and go to [http://127.0.0.1:8000](http://127.0.0.1:8000) to see the response.
### Step 4: Define a Data Model Using Pydantic FastAPI uses Pydantic to validate and serialize data. Let's create a simple model for a `Book` with a title and author.
from pydantic import BaseModel
class Book(BaseModel):
title: str
author: str### Step 5: Create CRUD Endpoints Let's create endpoints to add and read books stored in memory. We'll use a list to keep our books.
books = [] # Our in-memory database
@app.post("/books/")
def create_book(book: Book):
books.append(book)
return book
@app.get("/books/")
def get_books():
return booksHere, the `POST /books/` endpoint allows clients to add a new book, and the `GET /books/` endpoint returns the list of all books.
### Step 6: Test Your API With the server running, you can test your API using tools like curl, Postman, or directly from the interactive docs FastAPI generates.
Open your browser at [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs) to access the automatically generated Swagger UI. You can use it to try your `/books/` endpoints easily.
### Conclusion You have now built a simple RESTful API using FastAPI. From here, you can expand your API by connecting to databases, adding authentication, or deploying your app to the cloud. FastAPI’s simplicity and power make it a great choice for building APIs efficiently.