Combining multiple REST API requests into a single request?

I am developing a REST API for my application.

With this API, I can do something like update company or person information using PUT companies/1 and PUT persons/2 , families/3 , etc.

I want to use this API for regular synchronization with other applications. This will require hundreds of thousands of REST API requests, most of which are such updates. Each request takes very little time, but the latency of each individual request is quite a lot of time.

Is there a way I could create a REST API that can combine multiple requests at once. I could easily think of simply executing PUT with an array of paths and formdata, but it looks like someone should have developed a nicer solution.

Is there a best practice for combining several different requests in a REST API into one request to avoid latency, or is there a better way to handle this situation at all?

+5
source share
2 answers

Delay only adds a series of requests. Using concurrent queries could solve the problem.

There is no best practice.

  • You can send a PATCH with multiple items in the collection.
    PATCH /companies [{id:1, ...}, {id: 2, ...}, ...]
  • You can define a composite collection that can contain elements of different types.
    PATCH /resources [{id: 1, "rdf:type": "app:Company", ...}, {...}]

I don't like any of them, but it's just an opinion ...

+1
source

The Google Gmail API supports this, with a fairly robust, reusable API.

https://developers.google.com/gmail/api/guides/batch

In short, your API has a POST /batch endpoint, and in the request body you send several HTTP requests. Responses will also be encoded.
This requires server and client logic, but will be very versatile 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-- 
+2
source

Source: https://habr.com/ru/post/1204738/


All Articles