Monday, 19 March 2018

RESTful Web Services Tutorial 1 - Creating a REST API in Visual Studio(.Net C#)

I must say, I never knew how easy and clear this topic of REST API is untill I did it myself. If you have any issues, mention it in the comment box by the left of this page that says: 'Your Opinion Matters' and you will recieve needed assistance.

 
In this lesson we are going to cover the following
Watch the Video Lessons Here

What is RESTful Web Services?


First we anwer the question, what is a web service? A web service is is a piece of software or service that is accessible over the internet. A web services can also be used by other services or applications. For instance the weather service, or the currency exchange rates. If we go to Google and type '100USD to EUR', a web service is called which executes the function to carry out the convertion. Here, 4 things happen:
  • accept the input parameters which are (the currency to convert from, the currency to convert to, and the value to convert)
  • query a database to obtain the exchange rate between the two currencies
  • do the calculation
  • return the result(response) to the client
All of this is handled by a web service
These whole process is just the same as what happens during a function call. But in this case we give it a fancy name 'web service' because it happens seamlessly over the web.

Now there are two types of web services:
SOAP Web Services: SOAP stands for Simple Object Access Protocol and this is the traditional web service that have been around for some time. SOAP is based on XML. Read more about SOAP here.

REST Web Services: REST stands for Representational State Transfer and is a newer type of web service. REST said to be (not a protocol or standard) but an architechtural style. It support both XML and JSON. Read more about REST here.


What is REST API?


Again we need to answer the question, 'what is an API?'. API stands for Application Programmer's Interface and defined as 'a set of sub-routine definitions, tools and protocols for building a computer software'. An API is built using normal software development tools. But they are not complete applications. They are tools to be used by other applications or by a programmer in developing an application.
An API based on REST is called REST API or RESTful API.

Lets not get into the practical aspect as this would help make it clearer for you. We would build a REST API to solve the task below.


Task


Creaate a REST Web Service in .NET that exposes methods to
  • Return a list of employees
  • Return an employee based on employeeID paramenter


Soltion: Creating RESTful API in Visual Studio(Step by Step)


We would cover thes seven simple steps and at the end we would have a complete web service in .Net that we can access through a browser or any other REST client.
You can use Visual Studio 2013, 2015 or 2017.


Step 1: Create an Empty Web API project


When you are creatinga new project, make sure you select Web API project as shown in the Figure 1.


Figure 1: Web API Template

Give the applicaiton a name and Click OK

Figure 2: Choose Empty, Select Web API


Make sure that the Web API checkbox is selected then you can click OK to create the application.
At this point the folders structure of your application is shown in Figure 3

Figure 3: Folder Structure




Step 2: Test the Application


Build and run the application in Chrome or Firefox or any other browser and ensure that the the home page is displayed as shown below. (You can press F5 to run the application)
It opens the browser window and displays the error page shown in Figure 4. This is not a problem.

The error pages is displayed because we have not yet added any model, view or controller to our REST API.
Close the browser window and stop application from running.



Step 3: Add a Controller


Right-click on the Controller folder in the solution explorer and click on Add, an choose Controller
Choose - Web API 2 Controller - Empty

Figure 4: Adding Controller

Give it a name  EmployeeController



Step 4: Add a Model (Employee model)


A controller is another class in the Controllers folder of  the solution that inherits from ApiController class.
  • Right-click on the Model folder in the Solution Explorer and choose Add
  • Click on New and choose Class.
  • Enter the following code to the class to define our employee model.



      public class Employee
    {
        public int EmployeeId { get; set; }
        public string Name { get; set; }
        public string  City { get; set; }
    }
Listing 1: Employee Model Class



Step 5: Create a List of Employees


Create a hard-coded list of employees in the controller class. This is shown in Listing 2.



        List<Employee> employees = new List<Employee>()
        {
            new Employee{EmployeeId=1, Name="Kindson", City ="Akokwa"},
            new Employee{EmployeeId =2, Name="Oleander", City="Lagos"},
            new Employee{EmployeeId =3, Name="Saffron", City="Gbagada"}
        };
Listing 2: The Employees List



Step 6: Write the two Methods


The first method would be a method that returns a list of employees.
The second method would take a parameter of an employeeId and return a particular employee that matches that particular id.
The two methods is shown in Listing 3



        [HttpGet]
        public IEnumerable<Employee> getEmployees()
        {
            return employees;
        }


        [HttpGet]
        public IEnumerable<Employee> getEmployeeById( int id)
        {
            var Emp = from emp in getEmployees()
                      where emp.EmployeeId.Equals(id)
                      select emp;

            return Emp.ToList<Employee>();
        }
Listing 3: Methods to return list of employee and single employee


At this point the complete controller file would be like shown in Figure 5.

Figure 5: Final Controller File



Step 7: Modify the WebApiConfig.cs file


This file controls what the url that will be typed into the browser to access the data.
Replace routeTemplate code with this one:

api/{controller}/{action}/{id}

The complete WebAPIConfig.cs file  will be as shown below.

Figure 6: WebAPIConfig File

 At this point, we are ready to test our API


Step 8: Test the API 


  • Rebuild  and run the application.
  • Run the applicaiton by pressing F5.
  • The browser opens and displays an error page.

Now, in the browser address bar, append the following /api/Employee/getEmployees 
The output would be as shown in Figure 7.

Figure 7: Final Output
Also test for getEmployeeById
Now replace the url with this one /api/Employee/getEmployeeByID/1
If it displays a single record, then you have successfully completed this tutorial




Next Steps


I would like to let you know that working with Web API does not get more difficult than this. The next steps would also be as easy to follow as this one.
We would now learn about RestClient, which is a tool you use to test web services.
Thank you for reading!

For video lessons, subscribe to my YouTube channel on: Tech and Programming Lessons on YouTube