Akhil Sharma Akhil Sharma - 15 days ago 5
reST (reStructuredText) Question

Relationships in REST resources

I am new to REST API design. While designing the API, I got confused with resource relationships and need suggestions.

My API has a workflow and each workflow will have a task. I am not able to decide between keeping task as an independent resource or using it as a sub-resource. More precisely:

Workflow Resource:

/api/v1/workflow

Task Resource:

Option 1:
/api/v1/workflow/{workflowId}/tasks/{taskId}

Option 2:
/api/v1/tasks/{taskId}?workflowId=”123”

I went through some of the stack overflow links. Some say, queryString works as a filter and should be optional favoring the use of subresource while others prefer keeping tasks as an independent resource and making the api url small.

I feel there is yet another way where we can keep the taskId and workflowId mapping in our database and let the user use:

Option 3:
/api/v1/tasks/{taskId}.

But this seems like a big effort maintaining the mapping.

Suggestions?

Answer

There is no such thing as a 'subresource' in REST. Everything is its own resource. That said, it's a good idea to come up with urls that are meaningful to the user, and also convenient for yourself.

If tasks are always part of a workflow, there is nothing wrong with:

/workflow/abc/task/xyz

But this is also completely fine:

/task/xyz

This definitely looks unusual to me:

/tasks/{taskId}?workflowId=123?

Because what happens if I don't pass a workflowId? Generally query parameters are indeed used for searches. I can't say if this is necessarily unrestful, but it seems like a bad idea.

So between the first two there is no difference in terms of what's objectively better, or more restful. Clients shouldn't guess the url anyway, they should always be discovered.

I would personally go with the deeper structure because I think the urls are more useful and descriptive that way; but this is subjective.

Comments