Skip to main content

Creating API with MVC ApiController part 2

In my previous post I wrote about first steps in creating Rest-full API by using ApiController. Now it`s time to make next step and go a little bit dipper inside web services created in MVC. In this post I want to describe two very important aspect:
  • creating a real life scenario for web service implementation of POCO entity
  • extend presented scenario and make it asynchronous
To complete this tutorial one more class is needed. This class is a simple fake of some database which  is wrapper around a very few collections and allow all CRUD operation. Moreover the implementation of this fake database uses a singleton design pattern to prevent creating instance of it each time and maintain state between web service calls.

Code Snippet
  1. /// <summary>
  2.         /// Represents a fake database.
  3.         /// </summary>
  4.         public sealed class FakeDbContext
  5.         {
  6.             private static volatile FakeDbContext instance;
  7.             private static object syncRoot = new Object();
  8.  
  9.             private FakeDbContext()
  10.             {
  11.                 this.Users = new List<User>();
  12.                 this.Dictionary = new Dictionary<string, string>();
  13.             }
  14.  
  15.             public static FakeDbContext Instance
  16.             {
  17.                 get
  18.                 {
  19.                     if (instance == null)
  20.                     {
  21.                         lock (syncRoot)
  22.                         {
  23.                             if (instance == null)
  24.                                 instance = new FakeDbContext();
  25.                         }
  26.                     }
  27.  
  28.                     return instance;
  29.                 }
  30.             }
  31.  
  32.             public List<User> Users { get; set; }
  33.  
  34.             public Dictionary<string, string> Dictionary { get; set; }
  35.         }

The real life scenario that we want to implement is a simple web service which expose all CRUD operation and of course it`s base on REST. In the following class each API functions return the same type HttpResponseMessage which represent a standard HTTP response. This type contains two important properties: StatusCode - which represent a  HTTP response status code and Content - which store body of the response if any. The the easiest to produce a HttpResponseMessage is calling one of many build-in functions which are responsible for creating a fully qualified response based on several input parameter:
Code Snippet
  1. /// <summary>
  2.         /// Represent a controller for managing <see cref="User"/>.
  3.         /// </summary>
  4.         public class UserController : ApiController
  5.         {
  6.             public UserController()
  7.             {
  8.                 if (!FakeDbContext.Instance.Users.Any())
  9.                 {
  10.                     FakeDbContext.Instance.Users = new List<User>()
  11.                 {
  12.                     new  User(){ Id = 1, FirstName = "Roberto", LastName="Carlos", Email="robi_carlo@gmail.com"},
  13.                     new  User(){ Id = 2, FirstName = "Zinédine", LastName="Zidane", Email="zizu@live.com"},
  14.                     new  User(){ Id = 2, FirstName = "Peter", LastName="Schmeichel", Email="scheisse@yahoo.com"},
  15.                 };
  16.                 }
  17.             }
  18.  
  19.             // GET api/person
  20.             [HttpGet]
  21.             public HttpResponseMessage Get()
  22.             {
  23.                 return Request.CreateResponse<ReadOnlyCollection<User>>(HttpStatusCode.OK, FakeDbContext.Instance.Users.AsReadOnly());
  24.             }
  25.  
  26.             // GET api/person/5
  27.             [HttpGet]
  28.             public HttpResponseMessage Get(int id)
  29.             {
  30.                 var resultUser = FakeDbContext.Instance.Users.FirstOrDefault(u => u.Id == id);
  31.                 if (resultUser == null)
  32.                 {
  33.                     return Request.CreateErrorResponse(HttpStatusCode.NotFound, "User dones`t exists.");
  34.                 }
  35.  
  36.                 return Request.CreateResponse<User>(HttpStatusCode.OK, resultUser);
  37.             }
  38.  
  39.             // POST api/person
  40.             [HttpPost]
  41.             public HttpResponseMessage Post(User value)
  42.             {
  43.                 if (value == null)
  44.                 {
  45.                     return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Null User object.");
  46.                 }
  47.  
  48.                 // Checking user already exists in a list.
  49.                 if (FakeDbContext.Instance.Users.Contains(value))
  50.                 {
  51.                     return Request.CreateErrorResponse(HttpStatusCode.Conflict, "User already exists.");
  52.                 }
  53.                 else
  54.                 {
  55.                     FakeDbContext.Instance.Users.Add(value);
  56.                 }
  57.  
  58.                 return Request.CreateResponse(HttpStatusCode.Created);
  59.             }
  60.  
  61.             // PUT api/person/5
  62.             [HttpPut]
  63.             public HttpResponseMessage Put(int id, [FromBody] User value)
  64.             {
  65.                 if (value == null)
  66.                 {
  67.                     return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Null User object.");
  68.                 }
  69.  
  70.                 if (!FakeDbContext.Instance.Users.Any(u => u.Id == id))
  71.                 {
  72.                     return Request.CreateErrorResponse(HttpStatusCode.NotFound, "User dones`t exists.");
  73.                 }
  74.                 else
  75.                 {
  76.                     FakeDbContext.Instance.Users.Remove(value);
  77.                     FakeDbContext.Instance.Users.Add(value);
  78.                 }
  79.  
  80.                 return Request.CreateResponse(HttpStatusCode.OK);
  81.             }
  82.  
  83.             // DELETE api/person/5
  84.             [HttpDelete]
  85.             public HttpResponseMessage Delete(int id)
  86.             {
  87.                 var personToDelete = FakeDbContext.Instance.Users.FirstOrDefault(u => u.Id == id);
  88.                 if (personToDelete == null)
  89.                 {
  90.                     return Request.CreateErrorResponse(HttpStatusCode.NotFound, "User dones`t exists.");
  91.                 }
  92.                 else
  93.                 {
  94.                     FakeDbContext.Instance.Users.Remove(personToDelete);
  95.                 }
  96.  
  97.                 return Request.CreateResponse(HttpStatusCode.OK);
  98.             }
  99.         }

Now our service is ready to use and we run it and we can call each GET, POST, PUT and DELETE function by using any of HTTP Client.

Picture 1. Calling GET and POST API  from test HTTP Client.
Whole source code of the project is available here.

Thank you.

Popular posts from this blog

Playing with a .NET types definition

In the last few days I spent some time trying to unify structure of one of the project I`m currently working on. Most of the changes were about changing variable types because it`s were not used right way. That is why in this post I want to share my observations and practices with you. First of all we need to understand what ' variable definition ' is and how it`s different from ' variable initialization '. This part should be pretty straightforward:   variable definition  consist of data type and variable name only <data_type> <variable_name> ; for example int i ; . It`s important to understand how variable definition affects your code because it behaves differently depends weather you work with value or reference types. In the case of value types after defining variable it always has default value and it`s never null value. However after defined reference type variable without initializing it has null value by default. variable initialization  is

Using Newtonsoft serializer in CosmosDB client

Problem In some scenarios engineers might want to use a custom JSON serializer for documents stored in CosmosDB.  Solution In CosmosDBV3 .NET Core API, when creating an instance of  CosmosClient one of optional setting in  CosmosClientOptions is to specify an instance of a Serializer . This serializer must be JSON based and be of  CosmosSerializer type. This means that if a custom serializer is needed this should inherit from CosmosSerializer abstract class and override its two methods for serializing and deserializing of an object. The challenge is that both methods from  CosmosSerializer are stream based and therefore might be not as easy to implement as engineers used to assume - still not super complex.  For demonstration purpose as or my custom serializer I'm going to use Netwonsoft.JSON library. Firstly a new type is needed and this must inherit from  CosmosSerializer.  using  Microsoft.Azure.Cosmos; using  Newtonsoft.Json; using  System.IO; using  System.Text; ///   <

Using Hortonworks Hive in .NET

A few months ago I decided to learn a big data. This sounds very complex and of course it is. All these strange names which actually tells nothing to person who is new in these area combined with different way of looking at data storage makes entire topic even more complex. However after reading N blogs and watching many, many tutorials today I finally had a chance to try to write some code. As in last week I managed to setup a Hortonworks distribution of Hadoop today I decided to connect to it from my .NET based application and this is what I will describe in this post. First things first I didn`t setup entire Hortonworks ecosystem from scratch - I`d love to but for now it`s far beyond my knowledge thus I decided to use a sandbox environment provided by Hortonworks. There are multiple different VMs available to download but in my case I`ve choose a Hyper-V. More about setting this environment up you can read here . Picture 1. Up and running sandbox environment. Now whe