Python · Advanced level

Advanced level · Module 4: Building Web APIs with Flask · Lesson 3 of 5

Testing an API with the Flask Test Client

Check every endpoint automatically, including error cases, without starting a server.

In this lesson you will

  • Write pytest tests for Flask endpoints with the test client
  • Use a separate test database

Key concepts

test clienttest databasestatus code assertionregression

The lesson

Flask's test client sends requests to your application inside the test process: client.get('/products') returns a response whose status code and JSON you can assert on.

Tests must never touch real data. Configure the app to use a temporary SQLite file for tests, created fresh by a fixture each time.

Test the unhappy paths as carefully as the happy ones: missing fields, wrong types, unknown IDs and missing API keys should each return the right status code and message.

Step by step

  1. Create an app fixture that uses a temporary database.
  2. Write tests for GET endpoints, including a 404.
  3. Write tests for POST with valid and invalid data.
  4. Run the suite and fix any failures.

Practice activity

Write at least ten API tests covering success and error cases for every endpoint in your inventory API.

Expected result: A passing API test suite that runs without a server and without touching real data.

Check your understanding

  1. Why should API tests use a separate database?

    Show answer

    So that tests cannot damage real data and each test run starts from a known, clean state.

Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.