I'm developing a REST API for my application.
With this API I can do stuff like update a company or person details using PUT companies/1
and PUT persons/2
, families/3
, etcetera.
I want to use this API to do regular synchronization from other applications. This would involve hundreds of thousands of requests to the REST API, most of them such updates. Each request takes very little time, but the latency of each individual request adds up to quite a bit of time.
Is there any way in which I could create REST API which can combine multiple requests as once. I could easily think of simply doing a PUT with the an array of paths and formdata, but it seems like somebody should have already designed a nicer solution.
Is there a best practice for combining multiple different requests to a REST API into a single request to avoid the latency or is there a better way in general to handle a situation like this?
Google's Gmail API supports this, with a pretty solid, reusable API.
https://developers.google.com/gmail/api/guides/batch
Long story short, your API has a POST /batch
endpoint, and in the request body, you send multiple HTTP requests. The responses will be similarly encoded.
This requires server-side and client-side logic, but would be very generic and very reusable.
Example:
POST /batch HTTP/1.1
Content-Type: multipart/mixed; boundary=batch_foobarbaz
Content-Length: total_content_length
--batch_foobarbaz
Content-Type: application/http
GET /farm/v1/animals/pony
--batch_foobarbaz
Content-Type: application/http
PUT /farm/v1/animals/sheep
Content-Type: application/json
Content-Length: part_content_length
If-Match: "etag/sheep"
{
"animalName": "sheep",
"animalAge": "5"
"peltColor": "green",
}
--batch_foobarbaz
Content-Type: application/http
GET /farm/v1/animals
If-None-Match: "etag/animals"
--batch_foobarbaz--
Latency only adds up by series of requests. Using parallel requests would solve the problem.
There is no best practice here.
PATCH /companies [{id:1, ...}, {id: 2, ...}, ...]
PATCH /resources [{id: 1, "rdf:type": "app:Company", ...}, {...}]
I don't like neither of them, but that's just an opinion...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With