Today, we are going to learn something amazing. We are going to understand & implement a full-fledged application with WPF, Rest-API & Entity framework.
With that said, let us move on to our goal, the REST API Implementation.
We need to answer 2 questions.
- 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.
- public class ValuesController : ApiController
- {
-
- public IEnumerable<string> Get()
- {
- return new string[] { "value1", "value2" };
- }
-
-
- public string Get(int id)
- {
- return "value";
- }
-
-
- public void Post([FromBody]string value)
- {
- }
-
-
- public void Put(int id, [FromBody]string value)
- {
- }
-
-
- public void Delete(int id)
- {
- }
- }
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.
- 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.
- 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.
Let's see what we have in the database,
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.
- public class EmployeeController : ApiController
- {
-
-
-
-
-
- [HttpGet]
- public IHttpActionResult Get(int id)
- {
- try
- {
- using (EmployeeDBEntities entities = new EmployeeDBEntities())
- {
- var emp = entities.Employees.FirstOrDefault(em => em.ID == id);
- if (emp != null)
- {
- return Ok(emp);
- }
- else
- {
- return Content(HttpStatusCode.NotFound, "Employee with Id: " + id + " not found");
- }
- }
- }
- catch (Exception ex)
- {
- return Content(HttpStatusCode.BadRequest, ex);
-
- }
- }
- }
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.
-
-
-
-
-
- [HttpPost]
- public HttpResponseMessage Post([FromBody]Employee employee)
- {
- try
- {
- using (EmployeeDBEntities entities = new EmployeeDBEntities())
- {
- entities.Employees.Add(employee);
- entities.SaveChanges();
- var res = Request.CreateResponse(HttpStatusCode.Created, employee);
- res.Headers.Location = new Uri(Request.RequestUri + employee.ID.ToString());
- return res;
- }
- }
- catch (Exception ex)
- {
- return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
- }
- }
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
-
-
-
-
-
-
- [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);
- }
- }
![]()
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.
-
-
-
-
-
- [HttpDelete]
- public HttpResponseMessage Delete(int id)
- {
- try
- {
- using (EmployeeDBEntities entities = new EmployeeDBEntities())
- {
- var employee = entities.Employees.Where(emp => emp.ID == id).FirstOrDefault();
- if (employee != null)
- {
- entities.Employees.Remove(employee);
- entities.SaveChanges();
- return Request.CreateResponse(HttpStatusCode.OK, "Employee with id" + id + " Deleted");
- }
- else
- {
- return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Employee with id" + id + " is not found!");
- }
- }
- }
- catch (Exception ex)
- {
- return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
- }
- }
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!