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

Autocomplete control with ASP.NET MVC 4 and jQuery

Almost in each modern website project one of the feature is suggesting user possible items to select when he start typing one of them. Such functionality is done by using control named autocomplete . Under the hood  it consists of at least three elements: UI control which allow user to type some text - mainly this in HTML input of text type Server-side function which serves data to be auto-completed Client-side logic (written in JavaScript) which , by using AJAX, send request to the server asynchronously and then process the results. When we think about creating autocomplete control in ASP.NET MVC 4 we definitely should take a look at  jQueryUI framework. One of the feature of this framework is autocomplete control which enables users to quickly find and select from a pre-populated list of values as they type, leveraging searching and filtering. That sounds very good and is excellently what we are looking for. First step in autocomplete control  creation is creating a

Multithread processing of the SqlDataReader - Producer/Consumer design pattern

In today post I want to describe how to optimize usage of a ADO.NET SqlDataReader class by using multi-threading. To present that lets me introduce a problem that I will try to solve.  Scenario : In a project we decided to move all data from a multiple databases to one data warehouse. It will be a good few terabytes of data or even more. Data transfer will be done by using a custom importer program. Problem : After implementing a database agnostic logic of generating and executing a query I realized that I can retrieve data from source databases faster that I can upload them to big data store through HTTP client -importer program. In other words, data reader is capable of reading data faster then I can process it an upload to my big data lake. Solution : As a solution for solving this problem I would like to propose one of a multi-thread design pattern called Producer/Consumer . In general this pattern consists of a two main classes where: Producer class is respons

Full-Text Search with PDF in Microsoft SQL Server

Last week I get interesting task to develop. The task was to search input text in PDF file stored in database as FileStream. The task implementation took me some time so I decided to share it with other developers. Here we are going to use SQL Server 2008 R2 (x64 Developers Edition), external driver from Adobe, Full-Text Search technology and FileStream technology.Because this sems a little bit comlicated let`s make this topic clear and do it step by step. 1) Enable FileStream - this part is pretty easy, just check wheter You already have enabled filestream on Your SQL Server instance - if no simply enable it as in the picture below. Picture 1. Enable filestream in SQL Server instance. 2) Create SQL table to store files  - mainly ther will be PDF file stored but some others is also be allright. Out table DocumentFile will be created in dbo schema and contain one column primary key with default value as sequential GUID. Important this is out table contains FileStream