A simple REST API for managing a collection of books, built with FastAPI and SQLAlchemy.
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.
- 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
- 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
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
- Python 3.13 or higher
- pip (Python package manager)
- Clone or download the project:
cd RestApi_Python- Install dependencies:
pip install -r requirements.txtOr using the project configuration:
pip install fastapi pydantic sqlalchemy uvicorn pytest httpxThe project includes a comprehensive test suite with 21 test cases covering all CRUD operations and edge cases.
Run the test suite using pytest:
pytest test_books.py -vOr run with coverage report:
pytest test_books.py -v --cov=booksThe test suite is organized into 5 test classes:
- 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
- Retrieving books from an empty database
- Reading all books when data exists
- 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
- Successfully deleting an existing book
- Deleting a non-existent book (404 error handling)
- Attempting to delete the same book multiple times
- Complete CRUD workflow (Create → Read → Update → Delete)
- Multiple operations with multiple books
All tests pass successfully:
21 passed, 1 warning in 1.94s
Start the development server with Uvicorn:
uvicorn books:app --reloadThe API will be available at http://localhost:8000
The interactive API documentation will be available at http://localhost:8000/docs
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
}
]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 characterauthor: Required, 1-100 charactersdescription: Required, 1-100 charactersrating: Required, integer between 0-100
PUT /{book_id}Update an existing book's details.
Example:
PUT /1Request Body: Same as POST
DELETE /{book_id}Remove a book from the database.
Example:
DELETE /1Using 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/1The application uses SQLite with a file-based database (books.db). The database is automatically created on first run.
| 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) |
- 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
To add a new dependency, update both requirements.txt and pyproject.toml:
pip install new-package
pip freeze > requirements.txtThen update pyproject.toml with the new dependency and version.
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)
- 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