Learn Everything About REST API

Introduction

 
Today, we are going to learn something amazing. We are going to understand & implement a full-fledged application with WPF, Rest-API & Entity framework.
 
To give you an overview, our final solution is going to look  as follows:
  •  We are going to have 3 projects.

    • First one is DataAccessLayer which is going to contain an EntityFramework
    • Second is a WPF application which is our Presentation layer.
    • Then last but not least, a REST API project: API exposed between Presentation & DataAccess layer.

      • Note
        It is a good practice to have Rest API's project on a different solution, but this is just for learning purposes so we are keeping it in the same solution for ease of access.
 
The goal of this article:
  • This article is specific to the REST API. In the next article, we will learn about the Presentation layer. (We will learn each layer one by one as it is fairly complicated to keep everything in one article.) Now out of 3 layers, I have already covered the first layer which is DataAccesslayer. You can follow steps mentioned in DataAccessLayer -Implementation and be ready with DataAccesslayer.
With that said, let us move on to our goal, the REST API Implementation.
 
We need to answer 2 questions.
  • What is the REST API?

    •  It is called s RESTful API which uses HTTP requests & has methods to 
       GET  Fetches the records from DB  e.g. select queries
       PUT  Updates the records into DB  e.g. update queries
       POST  Creates the records into DB  e.g. insert queries
       DELETE  Deletes the records from DB  e.g. delete queries
  • When to use REST API?

    • Imagine you have a mobile application plus website & both of these applications are going to access the same database. In that case, it would be a foolish move for one to design & develop a database for both of these applications.
    • Rather, one can have a database placed at one point and expose the APIs to 'n' number of applications based on their requirements.
  • Advantages of having this architecture

    • Loose coupling
      With such design, modules won't be highly integrated with each other.

    • Extensible
      So if tomorrow the client decides to have a WPF application as well as website & a mobile app, then we won't have to create new DB just for WPF. Just expose API to WPF application & we are good to go.

  • The architecture
I trust this will have helped you to understand the basics of REST API.
 
Now it's time for some solid action.
 

Implementation

 
Step 1
 
Right click on solution explorer  => Add new Project => Select Asp.Net web Application
 
  • Next, Configure project. Name as per your desire & click create button.
 
  • Finally, Select Web API & hit create button.
 
 
After successful configuration, Web API will add HomeController & ValuesController in your project under the controller folder.
 
Note
You need to have IIS installed into your system.
 
Now run the project. It will be published on IIS and will open in a web browser.
  •  Localhost is your system & next to that is the port number(e.g. 44372) on which REST API is running. 
 
Open ValuesController
 
It has default Get, Post, Put & Delete interfaces.
  1. public class ValuesController : ApiController  
  2.     {  
  3.         // GET api/values  
  4.         public IEnumerable<string> Get()  
  5.         {  
  6.             return new string[] { "value1""value2" };  
  7.         }  
  8.   
  9.         // GET api/values/5  
  10.         public string Get(int id)  
  11.         {  
  12.             return "value";  
  13.         }  
  14.   
  15.         // POST api/values  
  16.         public void Post([FromBody]string value)  
  17.         {  
  18.         }  
  19.   
  20.         // PUT api/values/5  
  21.         public void Put(int id, [FromBody]string value)  
  22.         {  
  23.         }  
  24.   
  25.         // DELETE api/values/5  
  26.         public void Delete(int id)  
  27.         {  
  28.         }  
  29.     } 
Let's call a get method, which is returning string array of values "value1" & "value2"  and see if that's working. Paste the following URL in your web browser.
 
Note
Put your port number.
  1. https://localhost:44372/api/values   
 
Perfect, that tells us that we have successfully configured the Rest API.
 
Next, we are going to create a new controller for employee.
 
Right-click on Controllers folder => Add new controller => Name it EmployeeController.
 
 
Select Web API 2 Controller - Empty
 
 
Name it EmployeeController
 
 
It will add the following class EmployeeController extending ApiController class.
  1. public class EmployeeController : ApiController  
  2.    {  
  3.          
  4.    } 
Important Advice
 
 Kindly Install Postman to take full advantage of REST API.
 
Now we are going to start creating CRUD operations.
 
First things first. Add DataAccessLayer's reference to REST_API's project.
 
 
Let's see what we have in the database,
 
 
GET Interface
 
First, let's fetch employee details based on employee id. Remember, to fetch the details we have to use the get method.
  • The attribute [HttpGet] specifies it is a get method. By default, it is a get method even if you don't mention it.
  • Return type IHttpActionResult: returns status code, error details, response data in content in HTTP format
  • EmployeeDBEntities is our DbContext to fetch employee entity with data.

    • returns ok if there are any records.
    • returns not found error if no records are there.
    • returns an exception if the request is not processable.

  • If you pass the specific id of the employee then details of that employee are returned, if you pass nothing then details of all employees are returned.
  1. public class EmployeeController : ApiController  
  2.    {  
  3.         /// <summary>  
  4.        /// Filter out epmloyee whose details are asked   
  5.        /// </summary>  
  6.        /// <param name="id">id of employee</param>  
  7.        /// <returns>employee details of id</returns>  
  8.        [HttpGet]  
  9.        public IHttpActionResult Get(int id)  
  10.        {  
  11.            try  
  12.            {  
  13.                using (EmployeeDBEntities entities = new EmployeeDBEntities())  
  14.                {  
  15.                    var emp = entities.Employees.FirstOrDefault(em => em.ID == id);  
  16.                    if (emp != null)  
  17.                    {  
  18.                        return Ok(emp);  
  19.                    }  
  20.                    else  
  21.                    {  
  22.                        return Content(HttpStatusCode.NotFound, "Employee with Id: " + id + " not found");  
  23.                    }  
  24.                }  
  25.            }  
  26.            catch (Exception ex)  
  27.            {  
  28.                return Content(HttpStatusCode.BadRequest, ex);  
  29.   
  30.            }  
  31.        }  
  32.    } 
Let's make a Get request from PostMan:
  • 1st request: fetch details of all the employees, 
 
  • 2nd request, Fetch details whose employee id = 8.
  •  3rd Request, Fetch details of employee who doesn't exist
 
 
 And my friends, this is how you fetch details using REST API.
 
Next in line POST interface
  • Add the following method in EmployeeController
  • You can either use HttpResponseMessage or IHttpActionResult. I personally use IHttpActionResult because it is easy to use.
  • You must pass request parameters from body in the form of JSON.
  1. /// <summary>  
  2.         /// Creates a new employee  
  3.         /// </summary>  
  4.         /// <param name="employee"></param>  
  5.         /// <returns>details of newly created employee</returns>  
  6.         [HttpPost]  
  7.         public HttpResponseMessage Post([FromBody]Employee employee)  
  8.         {  
  9.             try  
  10.             {  
  11.                 using (EmployeeDBEntities entities = new EmployeeDBEntities())  
  12.                 {  
  13.                     entities.Employees.Add(employee);  
  14.                     entities.SaveChanges();  
  15.                     var res = Request.CreateResponse(HttpStatusCode.Created, employee);  
  16.                     res.Headers.Location = new Uri(Request.RequestUri + employee.ID.ToString());  
  17.                     return res;  
  18.                 }  
  19.             }  
  20.             catch (Exception ex)  
  21.             {  
  22.                 return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);  
  23.             }  
  24.         } 
 
Let's cross-check in DB,
 
 
This is how perfectionism works.  The record has been successfully inserted into the DB.
 
Next in line is the  put interface
  • Add the following method in EmployeeController class
  • The put has 2 parameters

    • Id against which we have to update the record. Pass through URL as params
    • The new information has to be updated. Pass object as JSON through raw data

  • Add update statement for each property, because you may not know which property user wants to update. Must check for null conditions.
Let's update Elon's surname to Tusk and his salary to 5555555
  1. /// <summary>  
  2.        /// Update details of employee based on id  
  3.        /// </summary>  
  4.        /// <param name="id"></param>  
  5.        /// <param name="emp"></param>  
  6.        /// <returns>updated details of employee</returns>  
  7.        [HttpPut]  
  8.        public HttpResponseMessage Put(int id, [FromBody] Employee emp)  
  9.        {  
  10.            try  
  11.            {  
  12.                using (EmployeeDBEntities entities = new EmployeeDBEntities())  
  13.                {  
  14.                    var employee = entities.Employees.Where(em => em.ID == id).FirstOrDefault();  
  15.                    if (employee != null)  
  16.                    {  
  17.                        if (!string.IsNullOrWhiteSpace(emp.FirstName))  
  18.                            employee.FirstName = emp.FirstName;  
  19.   
  20.                        if (!string.IsNullOrWhiteSpace(emp.LastName))  
  21.                            employee.LastName = emp.LastName;  
  22.   
  23.                        if (!string.IsNullOrWhiteSpace(emp.Gender))  
  24.                            employee.Gender = emp.Gender;  
  25.   
  26.                        if (emp.Salary != 0 || emp.Salary <= 0)  
  27.                            employee.Salary = emp.Salary;  
  28.   
  29.                        entities.SaveChanges();  
  30.                        var res = Request.CreateResponse(HttpStatusCode.OK, "Employee with id" + id + " updated");  
  31.                        res.Headers.Location = new Uri(Request.RequestUri + id.ToString());  
  32.                        return res;  
  33.                    }  
  34.                    else  
  35.                    {  
  36.                        return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Employee with id" + id + " is not found!");  
  37.                    }  
  38.                }  
  39.            }  
  40.            catch (Exception ex)  
  41.            {  
  42.                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);  
  43.            }  
  44.        } 
 
Superb! now let's cross-check that in the DB:
 
 
And Elon Musk is now Elon Tusk.
 
The Last one: DELETE Interface
 
Out of everything,  Get & Delete are the simplest ones.
  • Add the following function in EmployeeController
  • We need to pass the id of an employee whose record we want to delete.
  • Check if a record with the given id exists or not

    • If yes, then delete
    • else give response as a record not found.
  1. /// <summary>  
  2.       /// Deletes the respected employee based on id passed.  
  3.       /// </summary>  
  4.       /// <param name="id"></param>  
  5.       /// <returns>id of deleted employee</returns>  
  6.       [HttpDelete]  
  7.       public HttpResponseMessage Delete(int id)  
  8.       {  
  9.           try  
  10.           {  
  11.               using (EmployeeDBEntities entities = new EmployeeDBEntities())  
  12.               {  
  13.                   var employee = entities.Employees.Where(emp => emp.ID == id).FirstOrDefault();  
  14.                   if (employee != null)  
  15.                   {  
  16.                       entities.Employees.Remove(employee);  
  17.                       entities.SaveChanges();  
  18.                       return Request.CreateResponse(HttpStatusCode.OK, "Employee with id" + id + " Deleted");  
  19.                   }  
  20.                   else  
  21.                   {  
  22.                       return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Employee with id" + id + " is not found!");  
  23.                   }  
  24.               }  
  25.           }  
  26.           catch (Exception ex)  
  27.           {  
  28.               return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);  
  29.           }  
  30.       } 
 
Record of Elon Tusk is deleted. 
  •  What if we send the wrong id? As we have already managed that in our code above, it won't be an issue.
 
Let's cross-check in DB to confirm.
 
 
And Elon Tusk has been deleted from DB as well.
 
Awesome. Everything is in its right place.
 

Conclusion

 
This was a long article but there was so much to learn. 
 
I believe now you have all the answers that you were searching for.
 
Do follow REST APIs are they are easy to implement & don't require much configuration. Plus they are loosely coupled.
 
In this article, we learned
  • What is REST API & when to use it.
  • How to configure & implement REST APIs
  • What are the advantages of REST APIs
  • Different interfaces of REST APIs
  • How to handle invalid requests
  • HttpResponseMessage & IHttpActionResult
  • How to use Postman for REST APIs
We will learn how to bind these data with WPF in the next article.
 
If you have any queries feel free to comment below.
 
If you wish to connect, you can find me:
Thank you all and all the best.
 
Happy Coding!