Home > Software engineering >  How to merge multiple API calls into one call in REST API
How to merge multiple API calls into one call in REST API

Time:10-30

For instance, if I have an API call http://localhost:3006/[email protected]&password=xxxxxx&count=4&location=US and another API call http://localhost:3006/[email protected]&password=xxxxxx&count=2&usernames=abc,xyz. So, can I merge these two calls into one by doing something like http://localhost:3006/[email protected]&password=xxxxxx&count=4&location=US/cancel-request?count=2&usernames=abc,xyz. If Yes then how I can handle this in Node.js with express.

CodePudding user response:

I'd suggest making these operations a POST instead of a GET. Then, you can have one URL for a multi-operation and you can have a JSON payload in the body that contains an array of operations and their parameters:

http://localhost:3006/multi-operation

With a JSON payload that parses to this:

[
   {
       operation: "send-message",
       email: "[email protected]",
       password: "xxxxx",
       count: 4,
       location: "US"
   },
   {
       operation: "cancel-request",
       email: "[email protected]",
       password: "xxxxx",
       count: 2,
       usernames: ["abc","xyz"]
   }
]

This would also only be sending sensitive information such as passwords in the body of the request which is generally considered safer than putting them in the URL (where they might get logged by various infrastructure).

Note: In a REST API design, a GET request is not supposed to have "side-effects". It's supposed to retrieve some resource. Calling it 0 times, 1 time or 10 times should have the same effect on the server/world. So, independent of the desire to specify multiple operations in one API call, neither of these operations should have been a GET operation anyway because they both have side effects (they cause some change to occur). So, these should likely be POST operations. There are lots of good articles on when to use GET, POST, PUT, PATCH, etc... in a REST API. If you're confused by this, you can start with these articles or find many others with a search:

https://restfulapi.net/http-methods/

https://www.restapitutorial.com/lessons/httpmethods.html

  • Related