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

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

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

Persisting Enum in database with Entity Framework

Problem statement We all want to write clean code and follow best coding practices. This all engineers 'North Star' goal which in many cases can not be easily achievable because of many potential difficulties with converting our ideas/good practices into working solutions.  One of an example I recently came across was about using ASP.NET Core and Entity Framework 5 to store Enum values in a relational database (like Azure SQL). Why is this a problem you might ask... and my answer here is that you want to work with Enum types in your code but persist an integer in your databases. You can think about in that way. Why we use data types at all when everything could be just a string which is getting converted into a desirable type when needed. This 'all-string' approach is of course a huge anti-pattern and a bad practice for many reasons with few being: degraded performance, increased storage space, increased code duplication.  Pre-requirements 1. Status enum type definition