Category Archives: csharp

CSharp: POST Request to Query API and JSON Parsing

Use the System.Net.WebClient object to make a POST request in C#. For parsing JSON, you can use Json.NET by James Newton-King. Install both packages using the NuGet Package Manager. This code example posts a search for the text ‘Dog’ to the Query API. This example uses the text parameter, if you want to use the file parameter to upload a document as a search parameter you will need to use multipart/form content type, with for instance RestSharp client for .NET.

string apiKey = "your-apikey";
string iodURL = "";
WebClient webClient = new WebClient();
NameValueCollection formData = new NameValueCollection();
formData["apikey"] = apiKey;
formData["text"] = "Dog";
byte[] responseBytes = webClient.UploadValues(iodURL, "POST", formData);
UTF8Encoding enc = new UTF8Encoding();
string json = enc.GetString(responseBytes);

The JSON response is serialized using Json.NET into .NET Objects representing the JSON response as a DocumentList of Document type.

DocumentList documentList = JsonConvert.DeserializeObject(json);
List docs = documentList.Documents;
public class DocumentList
public List Documents { get; set; }
public class Document
public string Reference { get; set; }
public double Weight { get; set; }
public List Links { get; set; }
public string Index { get; set; }
public string Title { get; set; }
public Object Content { get; set; }

The above code will parse the JSON response from IDOL OnDemand.

"documents" : [{
"content" : { },
"index" : "news_eng",
"links" : [ "DOG" ],
"reference" : "",
"title" : "Stick Dog Wants a Hot Dog by Tom Watson - review",
"weight" : 89.5
"content" : { },
"index" : "news_eng",
"links" : [ "DOG" ],
"reference" : "",
"title" : "Dog attacks on children are tragic – but we can try to understand the triggers | Deborah Orr",
"weight" : 88.010000000000005

Access the properties as normal:

foreach (Document doc in docs)
Debug.WriteLine("doc.reference: " + doc.Reference);

To do a multipart/form-data POST request, the simplest way is to use a client like RestSharp, which you can install via NuGet:

string apiKey = @"your-apikey";
string iodURL = @"";
string file = @"C:\Users\user1\Documents\iod\TheSecretSpiritualHistoryOfCalculus_ScientificAmerican.pdf";
var client = new RestClient(iodURL);
var request = new RestRequest("", Method.POST);
request.AddParameter("apikey", apiKey);
request.AddFile("file", file);
RestResponse response = (RestResponse) client.Execute(request);
string content = response.Content;
Debug.WriteLine("status: "+ response.StatusCode + ", content: " + content);

Brian Grinstead wrote a great article on a Multipart form post in C# implementation, for those who are interested.