Skip to main content
In this lesson, we will create tests to verify the user creation functionality of our API using FastAPI’s TestClient. We simulate GET and POST requests to ensure that the API responds correctly.

Testing the Root Endpoint

Before testing user creation, we first verify that the API’s root endpoint is operational. The following test sends a GET request to the ”/” route and asserts that the response includes the message “Hello World” with a status code of 200.
Sample console output:

Testing the Create User Endpoint

Next, we validate the user creation route. This route expects a POST request to /users/ with JSON data containing an email and a password. Initially, a simple version of the test might look like this:
Sample output for test runs:
Now, update the test to send a POST request with a JSON payload. In our endpoint, the schema requires an email and password. We verify that the response status is 201 (Created).
The test output should confirm a status code of 201:

Validating the Response Schema

The user creation endpoint is designed to return data that follows a specific schema, including an ID, email, and a created_at timestamp. The expected Pydantic model is defined as follows:
To ensure that the response conforms to this schema, the test imports the schemas and instantiates a UserOut model with the returned JSON data. This method automatically validates the structure of the response.
Running this test will produce output similar to:

Handling Duplicate User Creation

At times, using the same email for multiple tests can trigger an IntegrityError due to a duplicate key violation. An example error message might be:
To avoid duplicate key errors, ensure that users are either removed from the database between tests or that you use unique email addresses for each test run.
You can run the following SQL command in PgAdmin to view current user entries:
After deleting the user entry with the email “hello123@gmail.com”, re-running the test should result in a successful user creation.

Final Test Code

Below is the consolidated version of our test code after all improvements:
Sample run confirming both tests pass:
This approach leverages FastAPI’s TestClient and Pydantic for automatic schema validation, reducing the need for multiple manual assertions and ensuring the correctness of the API responses.

Watch Video