Suppose you have a FastAPI app responsible for talking with database via sqlalchemy and retrieving data. The sqlalchemy models have some `relationship`s and the job of your app is exposing this database models with or without relationships based on the operation. You can't make use of relationship loading strategies (`'selectin'`, `'joined'` etc.) because FastAPI tries to convert the result to pydantic schemas and pydantic tries to load the relationship even though you don't need it to load for that specific operation. There are three things you can do:
1.*Define the loading strategy in your sqlalchemy models and create different pydantic schemas for the same entity including/excluding different fields. (i.e. if you don't need to load `Book.reviews` for specific endpoint, create a new pydantic schema for books without including `reviews`). After that, create different routes for returning correct schema. (`get_books_with_reviews`, `get_books_without_reviews` etc.)*<br/>
This is the easiest option. Once you decided how each field should be loaded, you only need to create different pydantic schema for loading different fields. The downside is that you will have a lot of schemas and maintaining them will be hard.
2.*Create a pydantic schema with all fields and declare some fields as nullable. Do not load anything by default in sqlalchemy models (`lazy='noload'`). Create different routes returning the same schema but inside the routes, manually edit the `query.options` to load different fields.*<br/>
This is what we were doing in our project. Only implementing the routes that we need 90% of the time was working fine for us. If we need more data, we were doing a second request to our API and merging the results. This becomes tedious after some time which is why we decided to move away from it.
Now that we have our database ready, let's create pydantic schemas
```python
# schemas.py
from pydantic import BaseModel
class ReviewSchema(BaseModel):
id: int
text: str
book_id: int
book: "BookSchema | None" = None
class BookSchema(BaseModel):
id: int
title: str
author_id: int
author: "AuthorSchema | None" = None
reviews: list[ReviewSchema] = []
class AwardSchema(BaseModel):
id: int
name: str
year: int
class AuthorSchema(BaseModel):
id: int
name: str
books: list[BookSchema] = []
awards: list[AwardSchema] = []
```
And lastly, we need to initialize FastAPI app to interact with our database. Let's create a very simple app for exposing `Author`s and `Review`s outside.
Let's test to see if we are at the same point. Run `uvicorn app:app --reload` then perform a GET request for `/authors` endpoint. You should see two authors returned:
Now, let's start implementing what's required to load different fields based on user input. First of all, we need to have a way to determine the relationships of our database models. Then we will use these relationships to generate pydantic schemas which represents loading options. We will then use these schemas as input to our endpoint and inside our endpoint, we will load required fields.
1. Define a `RelationshipLoader` class in `models.py`.
Alter the `Base` definition to inherit from `RelationshipLoader` class. With this way, all the other models inheriting from `Base` will be also subclass of `RelationshipLoader`.
```python
class Base(DeclarativeBase, RelationshipLoader):
pass
```
This is all we need to do for our sqlalchemy models. Now, let's implement the function for generating pydantic schemas dynamically.
You may notice that our endpoints are now accepting POST request. If you want to perform the same thing with GET request, you will need to convert the options to query params. I will explain how it can be done in my next post. Stay tuned!