DEV Community

Cover image for How to Build a Books CRUD API with FastAPI
Ife
Ife

Posted on • Updated on

How to Build a Books CRUD API with FastAPI

Introduction

FastAPI is a modern Python web framework which has gained popularity for its high-performance capabilities and development time. I like it for its overall simplicity compared to Django.

In this tutorial, I will guide you through building a library CRUD (Create, Read, Update, Delete) application using FastAPI. By the end of this guide, you will have a fully functional books API that allows users to manage books effortlessly.

Prerequisites

Before we dive into the development process, let's ensure you have the necessary tools in place:

  • Python (3.6+)

  • FastAPI

You can install FastAPI using the following command:

pip install fastapi
Enter fullscreen mode Exit fullscreen mode
  • Uvicorn

You can install Uvicorn using the following command:

pip install uvicorn[standard]
Enter fullscreen mode Exit fullscreen mode

Building the CRUD API

Setting Up the Project

Let's start by setting up the project structure:

  • Create a new directory for your project.

  • Create a virtual environment and activate it

python -m venv myenv

myenv\Scripts\activate.bat #for Windows
source myenv/bin/activate #for Mac OS and Linux
Enter fullscreen mode Exit fullscreen mode
  • Install FastAPI and Uvicorn in the virtual environment
pip install fastapi uvicorn[standard]
Enter fullscreen mode Exit fullscreen mode
  • Inside the project directory, create a file named books.py.

FastAPI provides a lot of features for software development. In books.py, import the required dependencies:

from fastapi import FastAPI, Body
Enter fullscreen mode Exit fullscreen mode
  • For this tutorial, I will use a book list object with information about the books
BOOKS = [ 
    {'title': 'Jane Eyre', 'author': 'Jane Austen', 'category': 'period drama'},
    {'title': 'Great Expectations', 'author': 'Charles Dickens', 'category': 'period drama'},
    {'title': 'Bourne Idemtity', 'author': 'Robert Ludlum', 'category': 'mystery/thriller'},
    {'title': 'DaVinci Code', 'author': 'Dan Brown', 'category': 'mystery/thriller'},
    {'title': 'The Match Girl', 'author': 'Charles Dickens', 'category': 'tragedy'}
]
Enter fullscreen mode Exit fullscreen mode
  • Instantiate the FastAPI app. This lets you use all the dependencies that come with FastAPI
app = FastAPI()
Enter fullscreen mode Exit fullscreen mode

Implementing CRUD Operations

CRUD stands for create, read, update and delete and each aligns with the HTTP verbs, post, get, put respectively.

  • Create (POST)

To create the endpoint for the CRUD operations, you will need app decorator, post attribute and the endpoint you want. In this case, the endpoint /books/create_book is static.

The function that follows takes new_book data of type JSON. Body() tells FastAPI that. It then adds the new data to the book list.

@app.post('/books/create_book')
async def create_book(new_book=Body()):
    BOOKS.append(new_book)
Enter fullscreen mode Exit fullscreen mode
  • Read (GET)

To get all the values from the BOOKS list, we use get.

@app.get('/books')
async def read_all_books():
    return BOOKS
Enter fullscreen mode Exit fullscreen mode
  • Update (PUT)

To update an entry in the books list, we use put. The function takes the updated data from the user and loops through the list. If the title of the updated entry matches a title in the list, the matching entry is updated. This means the title can't be changed since we are searching for entries through their titles.

@app.put('/books/update_book')
async def update_book(update_book=Body()):
    for i in range(len(BOOKS)):
        if BOOKS[i].get('title').casefold() == update_book.get('title').casefold():
            BOOKS[i] = update_book
Enter fullscreen mode Exit fullscreen mode
  • Delete (DELETE)

We use delete to delete the entry that matches the book title the user provides. This endpoint is not static as it has a dynamic parameter {book_title} of type string (str).

@app.delete('/books/delete_book/{book_title}')
async def delete_book(book_title: str):
    for i in range(len(BOOKS)):
        if BOOKS[i].get('title').casefold() == book_title.casefold():
            BOOKS.pop(i)
            break
Enter fullscreen mode Exit fullscreen mode

Running the App

Now that we are done building the app, the next step is to test it.

Uvicorn is the server used to run FastAPI locally on your machine. Use the following command to start the server

uvicorn main:app --reload
Enter fullscreen mode Exit fullscreen mode

Testing the Endpoints

FastAPI comes with automatic docs (Swagger UI and Redoc). You can access the docs through http://127.0.0.1:8000/docs or http://127.0.0.1:8000/redoc. Swagger UI doc looks like this.

Image description

You can test the API in the documentation.

The code for this project is live on Github

Conclusion

FastAPI helps developers to build APIs efficiently, and this tutorial has showcased its capabilities. In this tutorial, you learnt how to set up FastAPI routes and test your endpoints. In my next tutorial, I will cover dynamic path parameters and query parameters.

Was this tutorial helpful to you?

Top comments (0)