Updating Data with SQLAlchemy
Later in the article, we update an existing post. The following snippet retrieves a post by its ID, raises an exception if it’s not found, applies updates using new data, commits the changes, and returns the updated post:Refactoring the Endpoint for User Creation
To create a new user, modify the decorator to target the/users URL. In this refactoring, we switch from handling posts to managing user registration. For simplicity, we temporarily remove the response model.
Below is the refactored endpoint for user creation:
create_user clearly aligns with the endpoint’s purpose. Remember that when creating any resource, the default status code should be 201.
Defining the User Schema
When receiving registration data, the incoming JSON must include both an email and a password. We create a dedicated Pydantic schema to enforce required fields. Below are the model definitions for posts and the initial user creation schema:EmailStr. This ensures that the provided email follows a valid format. Make sure the email-validator library is installed (it comes automatically when installing FastAPI with the all flag, or you can install it via pip install email-validator).
Below is an updated version that uses EmailStr and improves date handling for posts:
email-validator when running pip freeze.
Returning a password in the response is not secure. Always ensure that sensitive information is excluded from API responses.
Implementing the Create User Endpoint
Back in the main application file, define the endpoint to create a new user by adapting the logic from the post creation operation. Notice how we convert the incoming Pydantic object to a dictionary and unpack it when instantiating the SQLAlchemy model, which facilitates proper insertion. The following snippet demonstrates the user creation endpoint:Testing the Endpoint via Postman
Use an API client like Postman to test the endpoint. Create a new POST request named “create user” and set the request body to raw JSON. For example, use the following payload:/users instead of /posts. When the request is sent, you should receive a response containing the user’s email, creation timestamp, and ID. For instance:
Validating Email Input
To ensure the email validator is working, try submitting a request with an invalid email format. In this case, the schema validator returns an error message similar to:Creating a Response Model for the User
To prevent sensitive information (like the password) from being returned in the API response, define a new Pydantic model calledUserOut. This model includes the user ID, email, and optionally the creation timestamp.
UserOut response model:
UserOut. For example:
created_at), ensure that your models are updated accordingly: