Rest API -> passing json string as parameter value - json

Is it the recommended way to pass a JSON string as a parameter value in a REST API?
This is the data which I am trying to send :
http://127.0.0.1:8000/v1/product/?productName=&metrics={"memory":2,"disk_space":10}
Here, is it ok to pass the value of metrics as JSON value?
Initially, I tried passing the metrics JSON value in the body. As it is not supported/recommended standard I have removed it.

Is it the recommended way to pass a JSON string as a parameter value in a REST API?
REST is an architectural style and it doesn't enforce (or even define) any standards for passing JSON string as a parameter value.
If you want to send JSON in the query string, you must URL encode it first:
/v1/products?productName=&metrics=%7B%22memory%22%3A2%2C%22disk_space%22%3A10%7D
Alternativelly, you could redesign the parameters to be like:
/v1/products?productName=&metrics.memory=2&metrics.diskSpace=10
If the URL gets too long (or the query gets too complex to be expressed in the query string), you may want to consider POST instead of GET, and then send the JSON in the request payload:
POST /v1/products/search HTTP/1.1
Host: example.com
Content-Type: application/json
{
"productName": "foo",
"metrics": {
"memory": 2,
"diskSpace": 10
}
}

Sending JSON values in GET request is not recommended. You can do it but metrics json can be long and anybody can read the content.
You should use POST request to send parameters such as productName and metrics in the body.
You should refer to this answer for detailed explanation.

For use Content-Type Application Json Please use below line
request.AddParameter("application/json", "{\n\t\"lastName\":\"gaurav.sablok#agarwalpackers.com\"\n}", ParameterType.RequestBody);
This is used with "RestSharp" name spaces

Related

Make a JSON object Without Quotes on the beginning and end of the string

I'm using React and fetch, and I'm trying to send a JSON string to a client's web service, they are expecting an object like this:
{
"id":"1",
"plan_id":"6",
"plan_start_date":"2017-08-02",
"months":"1",
"extra_hours":"4",
"attendees":"1",
"mails":"",
"shopping_cart_id":"0"
}
However, whenever I use JSON.stringify() to generate the JSON string, the result is something like this:
"{
"id":"1",
"plan_id":"6",
"plan_start_date":"2017-08-02",
"months":"1",
"extra_hours":"4",
"attendees":"1",
"mails":"",
"shopping_cart_id":"0"
}"
So when the request is sent, I get back an error stating that the object is not valid.
Is there a way to send the object like on the first example? I've tried manually building the object, but I can't get the key's names to stay in quotes.
EDIT: The code for the call is here:
addToCart(plan) { //Plan is the object with the previous example's structure
fetch("http:ClientWS", {
method: "POST",
body: JSON.stringify(plan) //Produces the "{}" issue
})
.then(response => response.json())
.then(json => {
//Read the response info, here it tells me that the value for 'id' is invalid
console.log(json.datos);
}).catch(function(ex) {
console.log(ex);
});
}
JSON.stringify() does not add extra quotes around the output. If you are seeing those extra quotes, I would say that it implies that the error is somewhere else.
That's because JSON.stringify takes your object and outputs a string variable by concatenating all the properties and values together and inserting some separators. And a string is displayed in quotes, again because it's a string. It's not an object any more. When you send it to the server, the server will see it as a single string value. The fact that the content of the string happens to look like JSON is not taken into consideration.
You do know that JSON and JavaScript objects are essentially the same thing? The stringified JSON that you can see is just a human-readable version of the object structure. It also turns out to be a convenient format in which to serialise objects (from all languages not just JS) for transmission in a HTTP request (or storage in a file or database, among other uses).
So actually when you send your object to the server, do just that - send the object. If you're doing it via ajax, the JS code you're using will generally serialise it for transmission on your behalf. You may have to set the correct content type header. That serialised object inside the HTTP request's body will end up looking a lot like the output of JSON.stringify (if you viewed it in your browser's network tab, for instance), except it won't actually be a string, and the server will interpret it correclty as an object containing multiple properties.

How to pass mongodb ObjectId() in HTTP request JSON body?

I need to send a mongo query in JSON typed request body, something like:
{ _id : { $gt : ObjectId("575d0c22964ddb3b6ba41bed") } }
(to get records inserted later than the id'ed record)
On the node server side I have express with body-parser middleware. It won't parse the request body JSON unless everything is quoted. E.g. the above has to be like:
{ "_id" : { "$gt" : "ObjectId(\"575d0c22964ddb3b6ba41bed\")" } }
The db runs the query with all the quotation marks and returns nothing.
How do I pass ObjectId() to mongodb as a function without re-parsing the whole request body and stripping off the quotation marks?
I'm testing with postman extension in Chrome, and sends the request to a REST url: /api/:obj_type/list.
The entire request body is used as a query.
you would be only passing around the string value in the client and server until a request is made the the database at which point you would make it a new ObjectID with the same value to be passed into the db. Passing around a string is a bit easier as all the clients/server know how to deal with a string vs ObjectID - also passing the ObjectID in a URL would be an issue. - To answer your question on how to pass the ObjectID() to Monogdb without re-parsing. You really wouldn't unless I'm misunderstanding the context
but pass around the ID as a string so it would be something like var stringId = "507f1f77bcf86cd799439011" and when you are about do a query you would do something along the lines of col.find({_id: new ObjectId(stringId)}).toArray(function(err,results){});

Get content from anyContent as Json

I have case class with field AnyContent. I get it from DB as
AnyContentAsText( //some value)
Than when I get it in JSON like text
Json.obj("body"->content.asText)
it returns
[{"body":"AnyContentAsJson({\"ma\":\"some#email.com\"})"}]
When I want get it like JSON
Json.obj(content.asJson)
I get
[null]
How can I get it like JSON but not null of course?
The only way to go from AnyContentAsText to JSON would be to simply do Json.parse(content.asText).
However, it's odd that you're getting a value from your DB as AnyContentAsText. AnyContentAsText and all other subclasses of AnyContent are really intended for the request lifecycle. When you consume a request in a controller method, the first thing you should be doing is parsing your AnyContent into the expected underlying value (text, json, etc.) and then do any business logic/persistence with those underlying values.
If you're receiving AnyContentAsText on the backend, check the request headers that the client sends.
I had forgotten the "Content-Type": "application/json" header on my POST with JSON content. After adding the header, I received AnyContentAsJson on the backend side, as expected.

Wrapping JSON payload with key in EmberJS

Ok basically I am sending a POST request with some JSON payload in it to Codeigniter. I use RESTAdapater. JSON get sent there with no key, so I have no access to it.
Here is model:
App.Bookmark = DS.Model.extend({
title: DS.attr("string"),
url : DS.attr("string")
});
Here is controller:
App.BookmarksNewController = Ember.ObjectController.extend({
save: function(){
this.get("model.transaction").commit();
this.get("target").transitionTo("bookmarks");
}
});
In REST implementation in CI that I use standard way to access the post request is $this->input("key"). But when the above request is generated, only raw JSON data is sent. Therefore I don't seem to have a way to reference it in any way.
Take this example:
function post(){
$this->response(var_dump(file_get_contents("php://input")),200);
}
Gives me this output:
string(48) "{"bookmark":{"title":"sdffdfsd","url":"sdfsdf"}}"
what I would like to see is:
string(48) payload="{"bookmark":{"title":"sdffdfsd","url":"sdfsdf"}}"
Then is server I would be able to access this JSON with something like $this->post("payload").
So 1 of 2. Anyway to wrap the JSON payload with key? Or anyway to access raw JSON data in CI with no key available??
Ok figured it out myself (or rather read properly the examples).
When using Adam Whitney's fork of Phil Sturgeons REST controller for CodeIgniter the JSON payload will be available in $this->_post_args. And in the underlying implementation he uses my already mentioned file_get_contents("php://input").
EDIT: Same convention applies for other type of requests as well, for example DELETE request data will be available in $this->_delete_args. Or $this->_args is the "magic" place where all types of args can be found.

is "HelloWorld" a valid json response

This could be the most basic json question ever. I'm creating a WCF REST service and have a HelloWorld test function that just returns a string. I'm testing the service in fiddler and the reponse body I'm getting back is:
"HelloWorld"
I also created a function that would just return a number (double) and the response body is:
1.0
Are those valid json responses? Are simple return types just returned in plain text like that (no markup with the brackets)?
Valid JSON responses start with either a { for an object or [ for a list of objects.
Native types are not valid JSON if not encapsulated. Try JSONlint to check validity.
RFC 4672, says no. Which doesn't mean it can't work, but it isn't strictly standards compliant. (Of course, neither are all the JSON readers...)
To quote from Section 2, "JSON Grammar":
A JSON text is a sequence of tokens. The set of tokens includes six
structural characters, strings, numbers, and three literal names.
A JSON text is a serialized object or array.
JSON-text = object / array
Only objects / maps, and arrays, at the top level.
According to the official website, you need to use a syntax like this:
You need to declare what you want beetween {}, like this:
{
"test": "HelloWorld"
}
No. The following is, for example:
{
"Foo": "HelloWorld"
}
You can try JSONLint to see what validates and what does not.