mlab (Mongolab) REST API calls in C#

Posted on October 17th, 2015 at 10:00 AM


Since we have been waxing lyrical about mlab's sandboxes here's a list of REST API calls we have found useful using C#:

using System.Net;
........
public const string MDApiKey = "apiKey=YOURMLABSAPIKEYSTRING";
public const string MDUrl = "https://api.mongolab.com/api/1/databases/";
public const string MDPath = "YOURDBNAME/collections/YOURCOLLECTIONNAME?";
........
WebClient webClient = new WebClient();
webClient.Headers[HttpRequestHeader.ContentType] = "application/json";
webClient.Headers["User-Agent"] = "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.2.6)" + 
    "Gecko/20100625 Firefox/3.6.6 (.NET CLR 3.5.30729)";
webClient.Headers.Add("referer", "http://YOURDOMAIN");
webClient.Proxy = new WebProxy("http://YOURISP-PROXY:YOURISP-PROXYPORT");
........
// query
string query = "q={ \"key\" : \"" + keyvalue + "\" }";   
string response = webClient.DownloadString(MDUrl + MDPath + query + "&" + MDApiKey);
........
// add new doc
string addjson = "{\"key0\":\"keyvalue0\",\"key1\":\"keyvalue1\", ..... \"keyN\":\"keyvalueN\" }";
string response = cli.UploadString(MDUrl + MDPath + MDApiKey, addjson);
........        
// update existing or NEW field in document matching query
string query = "q={ \"key\" : \"" + keyvalue + "\" }"; 
string updatejson = "{ \"$set\" : { \"" + tgtField + "\" :\"" + tgtValue + "\" } }";
// eg { "$set" : { "x" : 3 } }
// overload UploadString with PUT method
string response = cli.UploadString(MDUrl + MDPath + MDApiKey + "&" + query, "PUT", updatejson);
........          
// delete document matching query
string query = "q={ \"key\" : \"" + keyvalue+ "\"}";   
string response = cli.UploadString(MDUrl + MDPath + MDApiKey + "&" + query, "PUT", "[ ]");