0
0
FastAPIframework~30 mins

Testing with database in FastAPI - Mini Project: Build & Apply

Choose your learning style9 modes available
Testing with database in FastAPI
📖 Scenario: You are building a simple FastAPI app that manages a list of books. You want to write tests that use a temporary database so your real data stays safe.
🎯 Goal: Create a FastAPI app with an in-memory SQLite database for testing. Write a test that adds a book and checks it is stored correctly.
📋 What You'll Learn
Create a FastAPI app with SQLAlchemy models for books
Configure an in-memory SQLite database for testing
Write a test function that adds a book to the test database
Verify the book was added by querying the test database
💡 Why This Matters
🌍 Real World
Testing with a temporary database helps keep your real data safe and lets you check your code works correctly without side effects.
💼 Career
Many jobs require writing tests for web apps that use databases. Knowing how to set up test databases and write tests is a key skill for backend developers.
Progress0 / 4 steps
1
Set up the Book model and database
Create a SQLAlchemy Book model with id (integer primary key) and title (string) fields. Also create a SQLAlchemy Base class and an engine using SQLite in-memory database with URL sqlite:///:memory:. Use declarative_base() for Base.
FastAPI
Need a hint?

Use declarative_base() to create Base. Define Book class with id and title columns. Use create_engine with sqlite:///:memory: URL.

2
Create a sessionmaker for the test database
Create a SQLAlchemy SessionLocal variable using sessionmaker bound to the engine. Set autocommit=False and autoflush=False.
FastAPI
Need a hint?

Import sessionmaker and create SessionLocal with autocommit=False, autoflush=False, and bind it to engine.

3
Write a test function to add and query a book
Write a test function called test_add_book(). Inside it, create all tables using Base.metadata.create_all(bind=engine). Then create a session from SessionLocal(). Add a Book with title='Test Book' to the session, commit, and query the book back by filtering title='Test Book'. Assert that the queried book's title is 'Test Book'.
FastAPI
Need a hint?

Define test_add_book(). Create tables, open a session, add a book with title 'Test Book', commit, query it back, and assert the title matches.

4
Integrate FastAPI app with test database session
Create a FastAPI app instance called app. Define a dependency function get_test_db() that yields a session from SessionLocal() and closes it after use. Add a POST endpoint /books/ that accepts a JSON body with title and uses the get_test_db dependency to add a new Book to the database and return it.
FastAPI
Need a hint?

Create app = FastAPI(). Define get_test_db() dependency that yields a session and closes it. Add POST endpoint /books/ that accepts BookCreate model, adds a book to DB, commits, refreshes, and returns the book data.