Send request by JSON or String what get less resources - json

Actually question is not important.
For example there data to send by post request as:
{data: {"asd":"asdasd", "asd1":"asd1asd1"}}
Is something change if send it as string like:
{data: '{"asd":"asdasd", "asd1":"asd1asd1"}'}
or if is possible (string only):
'{data: {"asd":"asdasd", "asd1":"asd1asd1"}}'
So question is what type of those will get less resources or it will the same even with large data?

The longer your string is, the more bandwidth will it use. In which schema you need to send your data only depends on the receiver.
The only differences you have in your examples above are whether you send them as text or JSON. In the end, it will be sent as a string as the body of a HTTP Post request always is sent as a string, which means the bandwidth does not depend on how you send your object as it always will be a string. The receiver will then create a JSON object out of it upon receiving.
As you probably have the object as a javascript object (or whichever language you use) in your client where you'll send the request from, just use the JSON object whenever possible. The library you use should make sure that it takes a performant way of translating it to a string.

Related

Pass JSON object vs JSON string in HTTP POST

I'm building a REST API in JAVA and C# and I was wondering about the way I should pass data to those services.
What I'm familiar with as the right way is to send JSON object as the data in the POST body:
{name:'Dor'}
but I can also pass a string and parse the JSON in my service:
'{name:'Dor'}'
What is the preferable way from performance factor? or any other factors?
Basically, if you need to send the json data across via jquery, then we need to use stringify, else the data would be serialized into to key=value pair.
So, you cannot send the json object directly via jquery ajax method.
How it works behind the hood:
In $.ajax function, if we provide data as
data :{key1:"value1", key2:"value2"}
is serialized to key1=value1&key2=value2
if we provide data as
data :'{key1:"value1", key2:"value2"}' or JSON.stringify({key1:"value1", key2:"value2"})
is sent as {key1:"value1", key2:"value2"}
So, what we can conclude is that, we cannot pass json object directly via jquery, we can send only json string. Hope this clarifies everyone.

Make sure an incoming JSON response conforms to a schema?

I use Alamofire to interact with the server API via JSON requests/responses. I want to make sure server responds with some strictly formed payload to my requests.
How do I check that, for example, in {"responseCode":15, "data":{"username":"maxpayne", "fullname":"Max Payne", "score":154, friends:["johndoe", "franksinatra"]}}, responseCode is a number, username and fullname are strings, and friends is an array of strings?
I can do it manually for each response, but seems like it's going to be the most worthless time waste.
Alamofire has .validate() method but it is created for different purpose as what I see. I also had a look at JSONSchemaSwift which seems to be a right solution, but is not in active development.
As an alternative, it could be good to have a JSON deserializer which validates a response automatically and creates an object based on a Swift class I define.
May be a bit late, but this came out kylef/JSONSchema.swiftcame out on github. It's a JSONSchema validator, simple and effective.

Does using multipart/form-data Content Type for a RESTful POST api a good practice?

I have a situation where I have to write a api to create a resource and amongst datafields that I need to accept is a string that is basically contents of a html file. As I see it I have a choice between structuring the entire thing as a json object where this field is a string field with urlencoded html string , and having the Content Type as multipart/form-data where each of the fields and the html string (UTF-8 encoded) is a part in the message.
Not using json is something I am not comfortable with as I feel violating the REST standards in not structuring the content of the entity I am about to create thus there is a loss of information for the consumers as they can't tell immediately looking at my api definition about what data to feed to it. But practically multipart/form-data handles stuff like html file content better and more efficient as I will not have to urlencode it and can control the char-encoding also.
What will be a better approach in current context and upholding RESTful principles ? Also are there other trade-offs i should be aware of ? what about parsing a json with a huge string field (~ 200 Kb)embedded?
EDIT :- I was reading some similar questions on SO and one approach that stood out was the 2-step approach of making a first call with metadata to create the entity and then upload the file as an UPDATE process to the created entity wherein we use multipart/form-data. In that context, I guess , what I am asking is how sound is an approach where I send both metadata and the file in a single api call as multipart data , where each metadata field is actually a part in the multipart message as is the file.
The canonical way to upload files to REST API is using the multipart/form-data. As W3 recommendation guide says:
The content type "multipart/form-data" should be used for submitting
forms that contain files, non-ASCII data, and binary data.
Multipart/form-data has advantages over base64 to represent binary data. Is sticked to REST/Http philosophy, and simplify the develop of API clients.
Returning values from Forms: multipart/form-data
W3 Recommendation guide
The good practice is to use multipart/form-data whenever files are uploaded to the server along with database fields. Do not send a base64 JSON string as the request to your Rest API as it might corrupt the file or degrade the performance of your application.
As far as documenting multipart/form-data Rest API for your consumers is concerned you have to force your API consumers to use the same form fields which you have predefined in your web service.
Returning Values from Forms: multipart/form-data
I started using FormData objects everywhere on the client-side, in lieu of regular form input fields, for dynamic REST posts. FormData is presented in a positive light in various tutorials, so I went with it.
However, down the line, this caused me problems when decoding the form data into my Go structs. FormData objects are sent as "multipart/form-data" (regardless of files being sent) and I believe my decoder in Go didn't convert the raw data back to string form. Eventually my SQL queries were throwing panics, as hex data was being sent in where strings should have been.
So with some adjustment, I could use FormData however I've decided to revert to the simple universal recommendation: Use "multipart/form-data" only for special cases like when sending files. Otherwise, just use regular "application/x-www-form-urlencoded".

Should webhook JSON payloads be URL encoded?

New Relic currently URL encodes the JSON payload of our webhooks. We correctly include the necessary header, however, I'm wondering if this is best practice - or if the JSON payload should be sent un-encoded (or even with some different encoding)?
It's more common to send JSON directly in the request body with a Content-Type header value of application/json. It's not entirely uncommon to do it the way New Relic does however. GitHub post-receive hook payloads are also encoded this way.
In some languages/frameworks it's easier to extract the JSON data from a parameter than from reading the entire request body since form parameters are automatically parsed out and easily referenced and in some cases reading a request body may involve some more elaborate stream parsing.
An example of that is PHP's syntax for extracting the entire raw request body:
$data = file_get_contents('php://input');
var_dump(json_decode($data));
Versus extracting from a form parameter:
$data = $_POST["payload"];
var_dump(json_decode($data));
For frameworks that easily expose the request body, this isn't as much an issue. Here's the example given from the GitHub docs for handling the hook with Sinatra:
post '/' do
push = JSON.parse(params[:payload])
"I got some JSON: #{push.inspect}"
end
If the JSON body were passed directly, this is what it would look like:
post '/' do
push = JSON.parse(request.body.read)
"I got some JSON: #{push.inspect}"
end
It's mostly just an aesthetic preference, there's no technical advantage to either. With the parameter, you do get the flexibility of sending multiple JSON payloads in a single request or the option to send additional meta data outside the JSON. I would suggest sending a list of JSON objects and including all the meta data in a top level wrapper if that's important to you. Something like this:
{
"notification_id": "akjfd8",
"events": [ ... ]
}
I personally prefer raw JSON bodies, but that's mostly because it makes debugging far easier on sites like RequestBin. Your screenshot does a great job of illustrating how unreadable JSON encoded into a form parameter is.
<rant>
Payloads should be the content type you say they are. If they are sending as application/x-www-form-urlencoded then that is what you should expect to find. The culture of using a Russian doll model of nested encodings is beyond stupid in my opinion.
If you want to send JSON send it as application/json. Is that really so hard?
</rant>

Common practice to HTTP Form POST a JSON string instead of using key/value fields?

Is it a common practice to create an HTTP POST end point (with the header "application/x-www-form-urlencoded") that takes in a JSON string as the value of the key/value POST data instead of having a list of fields as the POST data? Regardless of being common or not, is it considered bad since it requires more work to stringify the fields into a JSON string?
Example:
user={"username":"bob", "age":1} vs username=bob&age=1 in the POST form data.
This is actually very common - the SOAP messaging format does just this; replacing the standard POST body with a custom messaging format (in the case of SOAP it is XML).
The only thing to consider is that HTTP is pretty ubiquitous these days and although it is trivial to find a JSON library for any language, creating a HTTP body is utterly simple.
So it isn't bad by any means, but if the client is serializing to JSON and then you are deserializing from JSON, would it just be easier to use standard HTTP message bodies?