question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

FastAPI POST/PUT Object with M2M relations

See original GitHub issue

Is your feature request related to a problem? Please describe. I’m using FastAPI in conjuction with Tortoise-orm, together with Pydantic.

With ForeignKeyField it’s pretty easy to add (POST) a new object, since it is treated as a normal field (and this is documented in the generated OPENAPI schema). When it comes to adding an object that has an M2M relation, it gets troublesome. Considering the example of the official docs https://tortoise-orm.readthedocs.io/en/latest/examples/basic.html#relations, one may need to add a new Team participating to an already existing Event. For this case, the generated OPENAPI docs show that one has to first create a new Team and only then add the M2M relation.

The solution is to separately add the M2M relation in a second step, via another path (e.g. /myapi/object/{id}/feature/). This can be done, but it may not be fully executed, leaving, in the case of a connection failure, a half added information. Also, it is not documented how to properly do it (which model should I use?).

Describe the solution you’d like A simple way to add a new object having an M2M relation in an ACID way. That is, all or nothing, especially since APIs rely on HTTP connections which are stateless and may be interrupted suddently.

Describe alternatives you’ve considered A clear and concise description of any alternative solutions or features you’ve considered.

Additional context Add any other context about the feature request here.

Thanks

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Comments:5

github_iconTop GitHub Comments

2reactions
metakotcommented, Jan 28, 2021

Well, you can do something like:

class TeamIn(BaseModel):
    name: str


class CreateTeamParams(BaseModel):
    team: TeamIn
    events: List[int]


class TeamOut(TeamIn):
    id: int
    events: List[int]


@api.post('/api/team',
    response_model=TeamOut,
)
async def create_team(
    params: CreateTeamParams = Body(...),
):
    team = await Team.create(**params.team.dict())
    events = await Event.filter(id__in=params.events).only('id')
    await team.events.add(*events)
    return TeamOut(id=team.id, name=team.name, events=params.events)
0reactions
lsabicommented, Jan 26, 2021

What stops me from implementing it, is the fact that I do not know how to implement that, starting from a tortoise.model and extending it.

There are fastapi docs, but they do not show how to insert new records in tables along with M2M relations, via an all-or-nothing approach.

As an example, one could take the one in the official docs https://tortoise-orm.readthedocs.io/en/latest/examples/basic.html#relations

Read more comments on GitHub >

github_iconTop Results From Across the Web

Many-To-Many Relationships In FastAPI - GormAnalysis
In this tutorial, I cover multiple strategies for handling many-to-many relationships using FastAPI with SQLAlchemy and pydantic.
Read more >
Models with Relationships in FastAPI - SQLModel
This will tell FastAPI to take the object that we return from the path operation function (a table model) and access the additional...
Read more >
FastAPI Course – Code APIs Quickly - freeCodeCamp
FastAPI makes it quicker and easier to develop APIs with Python. We just published a crash course on the freeCodeCamp.org YouTube channel ...
Read more >
How to populate ManyToMany field with POST request in ...
Having this models with ManyToMany relation in FastAPI app. I need to populate sent_log table with data from POST request:
Read more >
#pydantic - YouTube
FastAPI Tutorial 3: Data Validation, Optional & Objects as Parameters in FastAPI ... FastAPI Essentials - Creating a CRUD API with GET, POST,...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found