Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Posting a File and Associated Data to a RESTful WebService preferably as JSON

This is probably going to be a stupid question but I'm having one of those nights. In an application I am developing RESTful API and we want the client to send data as JSON. Part of this application requires the client to upload a file (usually an image) as well as information about the image.

I'm having a hard time tracking down how this happens in a single request. Is it possible to Base64 the file data into a JSON string? Am I going to need to perform 2 posts to the server? Should I not be using JSON for this?

As a side note, we're using Grails on the backend and these services are accessed by native mobile clients (iPhone, Android, etc), if any of that makes a difference.

like image 237
Gregg Avatar asked Nov 03 '10 02:11

Gregg


People also ask

How do I post a JSON file in REST API?

To post JSON to a REST API endpoint, you must send an HTTP POST request to the REST API server and provide JSON data in the body of the POST message. You also need to specify the data type in the body of the POST message using the Content-Type: application/json request header.

How do I send a file to REST API?

To attach a file, you must include it with the Body as form-data. Once you are in the Body → form-data fields, you must enter a KEY . This should be “file” or whichever value you specified in the @RequestPart(“[value]”) . After doing so, a dropdown will appear that gives you the option of Text or File.

Is JSON supported by RESTful services?

CICS JSON services can be converted into RESTful services using z/OS® Connect Enterprise Edition. A Graphical User Interface is used to map URI fragments and HTTP headers into fields of an existing copybook, and different programs can potentially act as the target for each HTTP method.

What is JSON and how is it used in RESTful APIs?

JSON is based on a subset of the JavaScript Programming Language. Representative State Transfer (REST) is a client-server architectural style that uses the HTTP protocol in a simple and effective way. Systems that adhere to REST practices are often referred to as RESTful interfaces.


1 Answers

I asked a similar question here:

How do I upload a file with metadata using a REST web service?

You basically have three choices:

  1. Base64 encode the file, at the expense of increasing the data size by around 33%, and add processing overhead in both the server and the client for encoding/decoding.
  2. Send the file first in a multipart/form-data POST, and return an ID to the client. The client then sends the metadata with the ID, and the server re-associates the file and the metadata.
  3. Send the metadata first, and return an ID to the client. The client then sends the file with the ID, and the server re-associates the file and the metadata.
like image 85
Daniel T. Avatar answered Oct 03 '22 12:10

Daniel T.