Has anyone explored using a single endpoint for their API?
On my team, we recently began using the included
array for updating multiple resources in a single PATCH
request:
http://example.com/people/1
{
"data": {
"type": "people",
"id": "1"
"attributes": {
"first-name": "Mike"
}
},
"included": [{
"type": "comments",
"id": "2",
"attributes": {
"body": "My updated comment!"
}
}
]
}
This made me realize that if we can update multiple resources using the included
array as an entry point, our API can act similarly, sending and receiving a data array of mixed types – so long as each object has a type
property and optionally an id
when using PATCH
or DELETE
.
For example, if we want to create multiple resources we can POST
to our single endpoint API:
http://example.com/api
{
"data": [{
"type": "people",
"attributes": {
"first-name": "Dan",
"last-name": "Gebhardt",
"twitter": "dgeb"
}
}, {
"type": "comments",
"attributes": {
"body": "First!"
}
}, {
"type": "comments",
"attributes": {
"body": "I like XML better"
}
}
]
}
A GET
of various resource, even those which do not have a relationship, can look like this:
{
"data": [{
"type": "people",
"id": "9"
}, {
"type": "comments",
"id": "5"
}, {
"type": "comments",
"id": "12"
}
]
}
I realize this may require some reworking of the request/response object structure, however I believe this approach allows for an API that closely resembles GraphQL and no longer requires the overhead of creating endpoints for every resource type.