restflaskforeign-keysflask-marshmallowflask-restx

General REST API: Insert Parent and Child at one request


I'm building a REST API with more or less complex resources.

So let's say, i have the following Database Structure behind the Scenes.

ParentBase: id|name

ChildBase: id|name|parentId

So, obviously column "parentId" of childBase is a foreignKey to ParentBase's id field.

Is it allowed to create a child with its parent at one post request and manage the realtionship serverside. My payload would look like the following and the url would be "/api/parents":

{
  id: <set by server>,
  name: Homer,
  {
    id: <set by server>,
    name: Lisa,
    parentId: <set by server (Homer's id)>
  }
}

Or do i have to create the parent first with a own post request and then take the returned id, set it to child's parentId and do a second post request with the child? So send to url "/api/parents":

{
  id: <set by server>,
  name: Homer
}

now I get the id=35 for Homer and I can send a second request to "/api/children" with payload:

{
  id: <set by server>,
  name: Lisa,
  parentId: 35
}

So what would be best practice?

(I'm using flask with sqlachemy and marshmallow. So maybe you also have an hint how to solve this task with these frameworks)


Solution

  • Is it allowed to create a child with its parent at one post request and manage the realtionship serverside.

    As far as REST and HTTP are concerned, sure.

    1. The details of the data structure behind the scene are implementation details, which we have deliberately hidden behind the HTTP facade; there is no rule that says your resource model needs to be 1:1 with your data model.
    2. Creating multiple resources in response to a single request is allowed

    The 201 (Created) status code indicates that the request has been fulfilled and has resulted in one or more new resources being created. -- RFC 7231