Skip to main content

Book Store


Implement a bookstore service to manage books and provide a RESTful API for CRUD operations.

Python implementation
from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

# In-memory database
books_db = []
book_id_counter = 0

# Book model
class Book(BaseModel):
id: int
title: str
author: str

# Get all books
def get_all_books():
return books_db

# Get a single book
def get_book(book_id: int):
for book in books_db:
if == book_id:
return book
return {"error": "Book not found"}

# Add a book"/books")
def add_book(title: str, author: str):
global book_id_counter
book_id_counter += 1
book = Book(id=book_id_counter, title=title, author=author)
return {"message": "Book added successfully"}

# Update a book
def update_book(book_id: int, title: str, author: str):
for book in books_db:
if == book_id:
book.title = title = author
return {"message": "Book updated successfully"}
return {"error": "Book not found"}

# Delete a book
def delete_book(book_id: int):
for book in books_db:
if == book_id:
return {"message": "Book deleted successfully"}
return {"error": "Book not found"}


Install dependencies
pip install fastapi pydantic uvicorn
Run the project
uvicorn main:app --reload --port 8000 # Use app from as the Web API instance
Test the API

FastAPI will automatically generate a Swagger documentation, you can access to test it using Swagger UI.