Skip to content

samisyd/Python_BookMgmt_RestApi

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 
 
 

Repository files navigation

RestAPI Python - Books API

A simple REST API for managing a collection of books, built with FastAPI and SQLAlchemy.

Overview

This project provides a RESTful API for performing CRUD (Create, Read, Update, Delete) operations on a books database. It demonstrates best practices for building modern Python APIs with FastAPI and SQLAlchemy ORM.

Features

  • Get all books - Retrieve a list of all books in the database
  • Add a book - Create a new book entry with title, author, description, and rating
  • Update a book - Modify an existing book's details
  • Delete a book - Remove a book from the database
  • Input validation - Pydantic models ensure data integrity
  • Database persistence - SQLite database for reliable data storage

Tech Stack

  • Framework: FastAPI - Modern, fast web framework for building APIs
  • ORM: SQLAlchemy - SQL toolkit and Object-Relational Mapping
  • Validation: Pydantic - Data validation using Python type annotations
  • Server: Uvicorn - ASGI web server
  • Database: SQLite - Lightweight, file-based SQL database

Project Structure

RestApi_Python/
├── books.py           # FastAPI application and route handlers
├── models.py          # SQLAlchemy database models
├── database.py        # Database configuration and setup
├── test_books.py      # Comprehensive test suite
├── requirements.txt   # Python dependencies
├── pyproject.toml     # Project metadata and configuration
└── README.md          # This file

Installation

Prerequisites

  • Python 3.13 or higher
  • pip (Python package manager)

Setup

  1. Clone or download the project:
cd RestApi_Python
  1. Install dependencies:
pip install -r requirements.txt

Or using the project configuration:

pip install fastapi pydantic sqlalchemy uvicorn pytest httpx

Testing

The project includes a comprehensive test suite with 21 test cases covering all CRUD operations and edge cases.

Running Tests

Run the test suite using pytest:

pytest test_books.py -v

Or run with coverage report:

pytest test_books.py -v --cov=books

Test Coverage

The test suite is organized into 5 test classes:

TestCreateBook (10 tests)

  • Valid book creation with all required fields
  • Edge cases (zero rating, maximum rating of 100)
  • Validation errors for missing fields
  • Validation errors for invalid data (author exceeding 100 characters, ratings outside 0-100 range)
  • Creating multiple books in sequence

TestReadBooks (2 tests)

  • Retrieving books from an empty database
  • Reading all books when data exists

TestUpdateBook (4 tests)

  • Successfully updating a book's information
  • Updating a non-existent book (404 error handling)
  • Attempting to update with invalid data
  • Updating specific fields while keeping others unchanged

TestDeleteBook (3 tests)

  • Successfully deleting an existing book
  • Deleting a non-existent book (404 error handling)
  • Attempting to delete the same book multiple times

TestIntegration (2 tests)

  • Complete CRUD workflow (Create → Read → Update → Delete)
  • Multiple operations with multiple books

Test Results

All tests pass successfully:

21 passed, 1 warning in 1.94s

Usage

Running the API

Start the development server with Uvicorn:

uvicorn books:app --reload

The API will be available at http://localhost:8000

The interactive API documentation will be available at http://localhost:8000/docs

API Endpoints

Get All Books

GET /

Returns a list of all books in the database.

Example Response:

[
  {
    "id": 1,
    "title": "The Great Gatsby",
    "author": "F. Scott Fitzgerald",
    "description": "A classic American novel",
    "rating": 95
  }
]

Create a Book

POST /

Add a new book to the database.

Request Body:

{
  "title": "1984",
  "author": "George Orwell",
  "description": "A dystopian novel",
  "rating": 92
}

Validation Rules:

  • title: Required, minimum 1 character
  • author: Required, 1-100 characters
  • description: Required, 1-100 characters
  • rating: Required, integer between 0-100

Update a Book

PUT /{book_id}

Update an existing book's details.

Example:

PUT /1

Request Body: Same as POST

Delete a Book

DELETE /{book_id}

Remove a book from the database.

Example:

DELETE /1

Example Requests

Using cURL:

# Get all books
curl http://localhost:8000/

# Create a book
curl -X POST http://localhost:8000/ \
  -H "Content-Type: application/json" \
  -d '{"title":"Sample Book","author":"John Doe","description":"A good book","rating":85}'

# Update a book
curl -X PUT http://localhost:8000/1 \
  -H "Content-Type: application/json" \
  -d '{"title":"Updated Title","author":"John Doe","description":"A good book","rating":90}'

# Delete a book
curl -X DELETE http://localhost:8000/1

Database

The application uses SQLite with a file-based database (books.db). The database is automatically created on first run.

Books Table Schema

Column Type Details
id Integer Primary key, auto-incremented
title String Book title
author String Book author
description String Book description
rating Integer Book rating (0-100)

File Descriptions

  • books.py: Main FastAPI application containing route handlers for all CRUD operations
  • models.py: SQLAlchemy model definition for the Books table
  • database.py: Database configuration, engine setup, and session management
  • test_books.py: Comprehensive test suite with 21 test cases covering all endpoints and edge cases
  • requirements.txt: List of Python package dependencies
  • pyproject.toml: Project metadata and package configuration

Development

Adding Dependencies

To add a new dependency, update both requirements.txt and pyproject.toml:

pip install new-package
pip freeze > requirements.txt

Then update pyproject.toml with the new dependency and version.

Error Handling

The API includes error handling for common scenarios:

  • 404 Not Found: Returned when trying to update or delete a book that doesn't exist
  • 422 Unprocessable Entity: Returned when request data fails validation (handled automatically by Pydantic)

Future Enhancements

  • User authentication and authorization
  • Search and filtering functionality
  • Pagination for large book collections
  • Book categories and genres
  • Rating and review system
  • Database migrations with Alembic

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages