Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

JanPe's avatar
Level 4

REST API Design for HasMany POST/PUT

Hi guys,

I need your support in API design. First of all, I am well aware of RESTFul, Resources Eloquent Relations. But I always find it difficult to find the ideal way for myself, as I can handle a HasMany relationship for POST / PUT requests.

How do you solve this in your projects?

An example:

The Workouts entity has exercises as children. The endpoint /api/vX/workouts is corresponding to CRUD.

Response GET /api/vX/workouts

{
    "data": [
        {
            "name": "",
            "other_attributes": "",
            "exercises": [
                {
                    "id": "",
                    "other_attributes": ""
                }
            ]
        }
    ],
    "Meta": {}
}

What would a POST / PUT look like if you wanted to create a relationship between workouts and exercises? I would like to avoid nested resources if possible.

Do you add the foreign_id to in the body of GET /api/vX/workouts or would you add it as a query parameter?

POST /api/vX/workouts

{
  "name": "",
  "exercises": [
    {
	"id": "foreign_id"
    }
  ]
}

or like POST /api/vX/workouts?exercise_ids=id1,id2,id3,,,

I know "it depends", but what do you prefer? The natural order would be to create the parent "workout" first and then to create the childs "exercise" and thus the parent_id in the childs body.

POST /api/vX/workouts

{
  "name": "",
  "other_attributes": "",
}

POST /api/vX/exercises

{
	"id_workout": "parent_id",
	"name": "",
}
0 likes
2 replies
bobbybouwmann's avatar

I would put the foreign key in the body of your request. So something like this

POST /api/vX/workouts

{
    "name": "",
    "exercise_ids": [ 14, 454, 78, 1 ]
}

With a simple array, you only need to send the IDs. That should be good enough in your case ;)

1 like

Please or to participate in this conversation.