Code Examples
See also this tutorial for more information about using the ASP.NET web API client libraries.
Making a GET request
Let's read orders created after a particular date. For security reasons, query results need to be paged, so we have to specify the $top option (and optionally $skip).
string publicKey = "0c6b33651708eb09c8a8d6036b79d739";
string secretKey = "3025c89ebaab20b71e0e42744239bf50";
string method = "get";
string accept = "application/json, text/javascript, */*";
string timestamp = DateTime.UtcNow.ToString("o"); // 2013-11-11T10:15:54.1731069Z
string url = "http://localhost:1260/odata/v1/Orders?$top=10&$filter=CreatedOnUtc gt datetime'2013-02-20T00:00:00'";
First, we create the message representation.
var uri = new Uri(url); // decode url
if (uri.Query != null && uri.Query.Length > 0)
{
url = string.Concat(uri.GetLeftPart(UriPartial.Path), HttpUtility.UrlDecode(uri.Query));
}
var messageRepresentation = string.Join("\n",
method.ToLower(),
"",
accept.ToLower(),
url.ToLower(),
timestamp,
publicKey.ToLower()
);
It looks like:
get
application/json, text/javascript, */*
http://localhost:1260/odata/v1/orders?$top=10&$filter=createdonutc gt datetime'2013-02-20t00:00:00'
2013-11-11T10:15:54.1731069Z
0c6b33651708eb09c8a8d6036b79d739
Now, we can calculate the HMAC signature by using our secret key.
We have all the information to set up the request, so we create a web request object and pass the required headers.
The complete header looks like this:
Making a POST request
Posting means inserting data via API. This example shows how to add a new order note "Hello world!" to the order with ID 152. Here is the function to create the MD5 hash of the request body:
No other variables have changed.
We add the same header fields as in the previous example, and additionally:
Then, we write the content into the request stream.
The message representation is as follows:
The header looks like this:
As a general rule, POST, PUT and PATCH are returning the added or changed record. For example:
Processing the response
Example of reading the response into a string:
JSON data can be easily parsed into dynamic or strongly typed objects using Json.NET. This example deserializes a JSON string into a list of customers.
Dynamic JSON parsing might look like this: