Steven
Steven

Reputation: 18859

Adding JSON as parameter in call to REST API

I'm using RestSharp to make calls to a REST API:

var client = new RestClient("http://mysite.com");        

var request = new RestRequest("/api/order", Method.POST);
request.AddHeader("AuthPass", "abcdefg1234567");

// add parameters here        

var response = client.Execute(request);
var content = response.Content;

I need to add parameters to the request. One is just my name, which is a string. The other is the list of orders items, which needs to be JSON in this format:

[
    {"SKU":"ABC-123", "QUANTITY":1},
    {"SKU":"XYZ-123", "QUANTITY":3}
]

I can add my name as a parameter like this:

request.AddParameter("name", "My Name");

But I don't know how to add the list of ordered items:

request.AddParameter("orderedItems", "???");

Anyone know how I can do this?

Upvotes: 1

Views: 1821

Answers (1)

bigtech
bigtech

Reputation: 484

If you make a class like this:

public class Orders
{
    public string SKU { get; set; }
    public string QUANTITY { get; set; }
}

then, you can make a list like so:

List<Orders> orderList = new List<Orders>
    {
        new Orders {QUANTITY = "1", SKU = "ABC-123"},
        new Orders {QUANTITY = "3", SKU = "XYZ-123"}
    };

and finally:

request.AddParameter("OrderList", orderList );

Upvotes: 1

Related Questions