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.

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.

Rest API

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 individually as keeping everything in one article is fairly complicated.) Out of 3 layers, I have already covered the first layer, the data access layer. You can follow the steps mentioned inDataAccessLayer -Implementation and be ready with DataAccessLayer.

With that we were 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

Method Description Example
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 a 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 the 'n' number of applications based on their requirements.

Advantages of having this architecture

The architecture

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

Add a new project

Next, Configure the project. Name as per your desire & click the create button.

Configure your new project

Finally, Select Web API & hit the Create button.

Create a new ASP dot net web application

After successful configuration, Web API will add HomeController & ValuesController in your project under the controller folder.

Note. You need to have IIS installed in 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.

ASP DOT NET

Open ValuesController

It has default Get, Post, Put & Delete interfaces.

public class ValuesController : ApiController
{
    // GET api/values
    public IEnumerable<string> Get()
    {
        return new string[] { "value1", "value2" };
    }

    // GET api/values/5
    public string Get(int id)
    {
        return "value";
    }

    // POST api/values
    public void Post([FromBody]string value)
    {
    }

    // PUT api/values/5
    public void Put(int id, [FromBody]string value)
    {
    }

    // DELETE api/values/5
    public void Delete(int id)
    {
    }
}

Let's call a get method, which returns a 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.

https://localhost:44372/api/values

XML file

Perfect, that tells us that we have successfully configured the Rest API.

Next, we are going to create a new controller for employees.

Right-click on Controllers folder => Add new controller => Name it EmployeeController.

Controller

Select Web API 2 Controller - Empty

Web API controller

Name it EmployeeController

Employee controller

It will add the following class EmployeeController extending the ApiController class.

public class EmployeeController : ApiController
{  
}

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.

Data access layer

Let's see what we have in the database.

DB employee

GET Interface

First, let's fetch employee details based on employee id. Remember, to fetch the details we have to use the get method.

Let's make a Get request from PostMan

And my friends, this is how you fetch details using REST API.

Next in line POST interface

Let's cross-check in DB

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

Let's update Elon's surname to Tusk and his salary to 5555555

/// <summary>   
/// Update details of employee based on id   
/// </summary>   
/// <param name="id"></param>   
/// <param name="emp"></param>   
/// <returns>updated details of employee</returns>   
[HttpPut]
public HttpResponseMessage Put(int id, [FromBody] Employee emp)
{
    try
    {
        using (EmployeeDBEntities entities = new EmployeeDBEntities())
        {
            var employee = entities.Employees.Where(em => em.ID == id).FirstOrDefault();
            if (employee != null)
            {
                if (!string.IsNullOrWhiteSpace(emp.FirstName))
                    employee.FirstName = emp.FirstName;

                if (!string.IsNullOrWhiteSpace(emp.LastName))
                    employee.LastName = emp.LastName;

                if (!string.IsNullOrWhiteSpace(emp.Gender))
                    employee.Gender = emp.Gender;

                if (emp.Salary != 0 || emp.Salary <= 0)
                    employee.Salary = emp.Salary;

                entities.SaveChanges();
                var res = Request.CreateResponse(HttpStatusCode.OK, "Employee with id " + id + " updated");
                res.Headers.Location = new Uri(Request.RequestUri + id.ToString());
                return res;
            }
            else
            {
                return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Employee with id " + id + " is not found!");
            }
        }
    }
    catch (Exception ex)
    {
        return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
    }
}

Select put

Superb! now let's cross-check that in the DB.

Cross check in DB

And Elon Musk is now Elon Tusk.

The Last one DELETE Interface

Out of everything, Get & Delete are the simplest ones.

The 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.

ID

Let's cross-check in DB to confirm.

Result

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

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!