Creating Generic RESTful API Services

Dominic Burford
Oct 20, 2017 · 3 min read
{"QuerySearchTerms":{"email":"test@mycompany.co.uk"}}
[DataContract]
public class WebQueryTasks
{
[DataMember]
public Dictionary<string, object> QuerySearchTerms { get; set; }

/// <summary>
/// Default constructor
/// </summary>
public WebQueryTasks()
{
this.QuerySearchTerms = new Dictionary<string, object>();
}
}
public string WebGetData(string queryname, string queryterms)
{
//initial checks such as validation and parameter checking

try
{
//deserialise the JSON array structure
WebQueryTasks query = ManagerHelper.SerializerManager().DeserializeObject<WebQueryTasks>(queryterms);
if (query == null || !query.QuerySearchTerms.Any())
{
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.BadRequest, new HttpError("Unable to deserialise search terms.")));
}

object temp;
string webResults;
//detemine the type of the query
switch (queryname.ToLower())
{
case WebTasksTypeConstants.GetCompanyByName:
webResults = this._userService.GetQuerySearchTerm("name", query);
if (!string.IsNullOrEmpty(webResults))
{
temp = this._companiesService.Find(webResults);
}
else
{
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.BadRequest, new HttpError("Unable to locate query search term(s).")));
}
break;
case WebTasksTypeConstants.GetUserByEmail:
webResults = this._userService.GetQuerySearchTerm("email", query);
if (!string.IsNullOrEmpty(webResults))
{
temp = this._userService.FindByEmail(webResults);
}
else
{
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.BadRequest, new HttpError("Unable to locate query search term(s).")));
}
break;
default:
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.BadRequest,
new HttpError($"Unknown query type {queryname}.")));
}
var result = ManagerHelper.SerializerManager().SerializeObject(temp);
return result;
}
catch (Exception ex)
{
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.BadRequest, new HttpError("Exception servicing request.")));
}
}

Dominic Burford

Written by

A father, cyclist, vegetarian, atheist, geek and multiple award winning technical author. Loves real ale, fine wine and good music. All round decent chap.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade