Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RESTful: creating multiple records in one request

Tags:

rest

I have a form that allows the user to send invites to others. The amount of invites is configurable by the user in the user interface, and could theoretically be infinite. The user needs to define an email address per invite.

When clicking 'send' it should ideally post one request to the server, wrapping all records in one bulk submit. Even though this is not truly RESTful (I heard), it seems favourable over sending possibly 50 separate requests. However, what would be the proper way to do this?

It gets tricky when one of the invites fails, due to a malformed email address or duplicate invites or so. It is fine to properly process the other valid requests, and provide errors on the invalid requests, but what response status code would one use for this?

Generally I try to use the JSONAPI request format. The errors would be in a top object called errors and would be an array consisting of multiple objects. The field key within an error object would point to the record index number (as received in the request) and field name of the error, i.e. "field": "/invites/0/email" for an error on the email field in the first received record.

like image 987
KrekkieD Avatar asked May 18 '14 08:05

KrekkieD


People also ask

Can an API return multiple responses?

No. In http, one request gets one response. The client must send a second request to get a second response.


1 Answers

The best solution I've seen to the "batch request" problem is Google Calendar's API. It is a RESTful API, and therefore there is a URL for every resource which you can manipulate using standard REST sematics (i.e. GET, POST, PUT, DELETE). But the API also exposes a "/batch" endpoint, which accepts a content-type of "mixed/multipart", and the request body contains several nested HTTP requests, each with their own headers, method, url and everything. The response is also one HTTP response with a content-type of "mixed/multipart" containing a collection of individual HTTP response, one response per request.

This advantage of this solution is that 1. It allows you to design your system in a RESTful manner, which we all know and love. 2. It generalizes well to any combination of HTTP requests that your system can deal with.

For more info see: https://developers.google.com/google-apps/calendar/batch

like image 122
gilsho Avatar answered Nov 14 '22 22:11

gilsho