Initial Implementation with Raw SQL
Below is an initial implementation that uses raw SQL commands to create a new post:Transitioning to SQLAlchemy ORM
SQLAlchemy provides an abstraction layer that eliminates the need to write direct SQL queries. Instead, you can leverage ORM models to handle database operations smoothly. When working with FastAPI, it is important to include the database dependency in your path operations, which simplifies unit testing and centralizes database management through dependency injection. Below is an updated example using FastAPI’sDepends to pass the database session:
Defining the ORM Model
For the ORM approach, define models that represent your database tables. The example below shows how thePost model is structured:
models.Post.
Creating a New Post Using SQLAlchemy
To create a new post, populate the SQLAlchemy model with attributes (title, content, published) provided by the request object. The following updated endpoint demonstrates how to create a new post using ORM:id and created_at.
The corrected handler is shown below:
Simplifying with Dictionary Unpacking
Manually mapping each attribute from the Pydantic model to the SQLAlchemy model can be tedious as the number of fields increases. Sincepost is an instance of a Pydantic model, you can convert it to a dictionary using post.dict(). By leveraging Python’s dictionary unpacking, you can simplify the creation of the ORM model instance:
**post.dict() automatically unpacks the dictionary into keyword arguments that match the fields defined in your Post model. This method is scalable and easier to maintain when additional fields are introduced.
Check that your model is defined accurately. The fields in your Pydantic model should directly correspond to the fields in your SQLAlchemy model for seamless data mapping.
Final Endpoint Implementation
After consolidating the improvements, your cleaner and final endpoint implementation is as follows:Remember to always commit your database session after adding new entries. Missing a commit could result in data not being persisted in the database.