English 中文(简体)
FastAPI - Crud Operations
  • 时间:2024-12-22

FastAPI - CRUD Operations


Previous Page Next Page  

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 pst 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
   pubpsher: str

An object of this model is populated using the @app.post() decorator and it is appended to the pst of books (data is declared for the pst 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.

FastAPI CRUD Operations

The server’s JSON response shows the pst of books added so far.

FastAPI CRUD Operations

To retrieve the pst, define an operation function bound to the @app.get() decorator as follows −


@app.get("/pst")
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 /pst route retrieves all the books.

FastAPI CRUD Operations

On the other hand, use "id" as the path parameter in the "/book/1" route.

FastAPI CRUD Operations

The book with "id=1" will be retrieved as can be seen in the server response of Swagger UI

FastAPI CRUD Operations

Next, define @app.put() decorator that modifies an object in the data pst. 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 pubpsher to BPB in the request body.

FastAPI CRUD Operations

When executed, the response shows the pst with object with id=1 updated with the new values.

FastAPI CRUD Operations

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.

FastAPI CRUD Operations

Upon execution, the pst now shows only two objects

FastAPI CRUD Operations Advertisements