FastAPI – CRUD Operations
”;
The REST architecture uses HTTP verbs or methods for the operation on the resources. The POST, GET, PUT and DELETE methods perform respectively CREATE, READ, UPDATE and DELETE operations respectively.
In the following example, we shall use a Python list as an in-memory database and perform the CRUD operations on it. First, let us set up a FastAPI app object and declare a Pydantic model called Book.
from fastapi import FastAPI from pydantic import BaseModel app = FastAPI() data = [] class Book(BaseModel): id: int title: str author: str publisher: str
An object of this model is populated using the @app.post() decorator and it is appended to the list of books (data is declared for the list of books)
@app.post("/book") def add_book(book: Book): data.append(book.dict()) return data
In the Swagger UI, execute this operation function a couple of times and add some data.
The server’s JSON response shows the list of books added so far.
To retrieve the list, define an operation function bound to the @app.get() decorator as follows −
@app.get("/list") def get_books(): return data
To retrieve a book with its id as a path parameter, define the get() operation decorator and get_book() function as below −
@app.get("/book/{id}") def get_book(id: int): id = id - 1 return data[id]
The /list route retrieves all the books.
On the other hand, use “id” as the path parameter in the “/book/1” route.
The book with “id=1” will be retrieved as can be seen in the server response of Swagger UI
Next, define @app.put() decorator that modifies an object in the data list. This decorator too has a path parameter for the id field.
@app.put("/book/{id}") def add_book(id: int, book: Book): data[id-1] = book return data
Inspect this operation function in the swagger UI. Give id=1, and change value of publisher to BPB in the request body.
When executed, the response shows the list with object with id=1 updated with the new values.
Finally, we define the @app.delete() decorator to delete an object corresponding to the path parameter.
@app.delete("/book/{id}") def delete_book(id: int): data.pop(id-1) return data
Give id=1 as the path parameter and execute the function.
Upon execution, the list now shows only two objects
”;