How to Do Http-Request/Call with JSON Payload from Command-Line

How to do HTTP-request/call with JSON payload from command-line?

Use curl, assuming the data is POST'ed, something like

curl -X POST http://example.com/some/path -d '{"version": "1.1", "method":"progr","id":2,"params":{"call":...} }'

If you're just retrieving the data with a GET , and don't need to send anything bar URL parameters,
you'd just run curl http://example.com/some/path

How do I POST JSON data with cURL?

You need to set your content-type to application/json. But -d (or --data) sends the Content-Type application/x-www-form-urlencoded, which is not accepted on Spring's side.

Looking at the curl man page, I think you can use -H (or --header):

-H "Content-Type: application/json"

Full example:

curl --header "Content-Type: application/json" \
--request POST \
--data '{"username":"xyz","password":"xyz"}' \
http://localhost:3000/api/login

(-H is short for --header, -d for --data)

Note that -request POST is optional if you use -d, as the -d flag implies a POST request.


On Windows, things are slightly different. See the comment thread.

Curl GET request with json parameter

This should work :

  curl -i -H "Accept: application/json" 'server:5050/a/c/getName{"param0":"pradeep"}'

use option -i instead of x.

How to process the payload send to an API

There is a big distinction between a REST API and a piece of software that merely "CALLS" the REST API. The following is a way to create the REST API itself, using only vbScript. This API can reside at a url ending with myrestapi.asp. When some other progrem calls your "end point" and sends a GET or POST request, you could perform any number of interesting tasks on your server, notably interacting with your MSSQL database, before returning whatever it was to be returned, as a JSON string. (THEN, it would be up to your interlocutor to figure out your answer by parsing that JSON. -- But I stress, THAT task is NOT the focus of this post.)

The following relies on the totally free ASPJSON parser (with Response.LCID = 1033).

It also briefly shows the use of Window's command-line curl to run tests.

One of the problems with vbScript is that it is so old, people assume "api-related" problems must mean you're using vbScript to send a command to an end point and get something back in JSON, and a lot of folks ask about and talk about how to do that.

But it's also possible (as I've recently discovered) to create the endpoints THEMSELVES. The difference is that when you are only ACCESSING an API, you are always dealing with structured data. When you ARE the API, if the data coming in is a JSON string, it is UNstructured. It is not a part of a name-value pair.

But it is very possible, with only a little work, to build such a piece of software using only vbScript. The api reads its Request object, bringing in the raw binary data in a format that can be easily converted to a standard vbscript string. At that point, the JSON parser is called, the result of which is the JSON fields, attached to a vbScript object. The retrieval syntax is very concise. Here's a very simple example login with email and password.

Dim tb,br,i,s,jsonObj,incomingParams,email,password,status
tb = Request.TotalBytes
br = Request.BinaryRead(tb)
s = ""

For i = 1 To tb
s = s & Chr(AscB(MidB(br, i, 1)))
Next
' s now contains JSON input
Set jsonObj = New JSONobject ' see note above
Set incomingParams = jsonObj.parse(s)
email = incomingParams("useremail")
password = incomingParams("userpassword")
status = checkEmail email,password ' pre-canned verification function
If status = "good" Then
key = getKey ' precanned routine to get random unique key
jout = "{""loginstatus"":""" & status & """,""loginkey"":""" & key & """}"
Else
key = 0
jout = "{""loginstatus"":""1""}"
End If
Response.ContentType = "application/json"
Response.Write(jout)

And that's it. To try this out, open a Windows cmd window and type:

curl -d "{\useremail\":\"memberemail@gmail.com\",\]"userpassword\":\"rawpassword\"}" -H Content-Type: application/json" https://www.myserver.com/myrestapi.asp

Hit Enter and if you have used an accepted email/password and if you typed the appropriate location for your API endpoint that you're testing, you should see two JSON fields in return, loginstatus, with a 0 (good status) and loginkey with a random sequence, your key.

So now you have your own REST API (of sorts) which CAN be expanded to support a full range of GETs and POSTs. I realize there are a lot of things classic ASP is lacking and that it is often possible to use a more modern language when programming in vbScript. Nevertheless, it's also possible to pull something off in vbScript.

How to pass payload via JSON file for curl?

curl sends POST requests with the default content type of application/x-www-form-urlencoded. If you want to send a JSON request, you will have to specify the correct content type header:

$ curl -vX POST http://server/api/v1/places.json -d @testplace.json \
--header "Content-Type: application/json"

But that will only work if the server accepts json input. The .json at the end of the url may only indicate that the output is json, it doesn't necessarily mean that it also will handle json input. The API documentation should give you a hint on whether it does or not.

The reason you get a 401 and not some other error is probably because the server can't extract the auth_token from your request.

HTTP post with JSON payload body containing an empty line using cURL

I suggest using --data-binary with curl to maintain the line breaks.

From here https://ec.haxx.se/http-post.html

POSTing binary When reading from a file, -d will strip out carriage
return and newlines. Use --data-binary if you want curl to read and
use the given file in binary exactly as given:

curl --data-binary @filename http://example.com/

pass JSON to HTTP POST Request

I think the following should work:

// fire request
request({
url: url,
method: "POST",
json: requestData
}, ...

In this case, the Content-type: application/json header is automatically added.

How to pass json POST data to Web API method as an object?

EDIT : 31/10/2017

The same code/approach will work for Asp.Net Core 2.0 as well. The major difference is, In asp.net core, both web api controllers and Mvc controllers are merged together to single controller model. So your return type might be IActionResult or one of it's implementation (Ex :OkObjectResult)


Use

contentType:"application/json"

You need to use JSON.stringify method to convert it to JSON string when you send it,

And the model binder will bind the json data to your class object.

The below code will work fine (tested)

$(function () {
var customer = {contact_name :"Scott",company_name:"HP"};
$.ajax({
type: "POST",
data :JSON.stringify(customer),
url: "api/Customer",
contentType: "application/json"
});
});

Result

Sample Image

contentType property tells the server that we are sending the data in JSON format. Since we sent a JSON data structure,model binding will happen properly.

If you inspect the ajax request's headers, you can see that the Content-Type value is set as application/json.

If you do not specify contentType explicitly, It will use the default content type which is application/x-www-form-urlencoded;


Edit on Nov 2015 to address other possible issues raised in comments

Posting a complex object

Let's say you have a complex view model class as your web api action method parameter like this

public class CreateUserViewModel
{
public int Id {set;get;}
public string Name {set;get;}
public List<TagViewModel> Tags {set;get;}
}
public class TagViewModel
{
public int Id {set;get;}
public string Code {set;get;}
}

and your web api end point is like

public class ProductController : Controller
{
[HttpPost]
public CreateUserViewModel Save([FromBody] CreateUserViewModel m)
{
// I am just returning the posted model as it is.
// You may do other stuff and return different response.
// Ex : missileService.LaunchMissile(m);
return m;
}
}

At the time of this writing, ASP.NET MVC 6 is the latest stable version and in MVC6, Both Web api controllers and MVC controllers are inheriting from Microsoft.AspNet.Mvc.Controller base class.

To send data to the method from client side, the below code should work fine

//Build an object which matches the structure of our view model class
var model = {
Name: "Shyju",
Id: 123,
Tags: [{ Id: 12, Code: "C" }, { Id: 33, Code: "Swift" }]
};

$.ajax({
type: "POST",
data: JSON.stringify(model),
url: "../product/save",
contentType: "application/json"
}).done(function(res) {
console.log('res', res);
// Do something with the result :)
});

Model binding works for some properties, but not all ! Why ?

If you do not decorate the web api method parameter with [FromBody] attribute

[HttpPost]
public CreateUserViewModel Save(CreateUserViewModel m)
{
return m;
}

And send the model(raw javascript object, not in JSON format) without specifying the contentType property value

$.ajax({
type: "POST",
data: model,
url: "../product/save"
}).done(function (res) {
console.log('res', res);
});

Model binding will work for the flat properties on the model, not the properties where the type is complex/another type. In our case, Id and Name properties will be properly bound to the parameter m, But the Tags property will be an empty list.

The same problem will occur if you are using the short version, $.post which will use the default Content-Type when sending the request.

$.post("../product/save", model, function (res) {
//res contains the markup returned by the partial view
console.log('res', res);
});


Related Topics



Leave a reply



Submit