Building A Restful API In ASP.NET

Let’s have a quick review of ASP.NET MVC Architecture. So when the request arrives at our application MVC Framework hands off that request to an action in a controller, this action most of the time returns view which is then parsed by razor view engine and then eventually html markup is returned to the client. So in this approach html markup is generated on the server and then returned to the client.

ASP.NET

There is an alternative way to generate the html markup, we can generate it on the client. So instead of our action returning html markup, they can return raw data.

ASP.NET

What is the benefit of this approach?

There are a number of benefits of generating markup on the client.

  • It requires less server resources (it potentially improves the scalability of the application because each client will be responsible for generating their own views)
  • Raw Data often requires less bandwidth than html markup. So the data potentially arrives faster at the client. And this can improve the perceived performance of the application.
  • This approach supports the broad range of clients like mobile and tablet apps.

These apps are simply called endpoints get the data and generate the view locally. We call these end points Data Services (Web APIs) because they just return data not markup.

Web APIs are not just limited to cross devices, it also iswidely used in our Web Applications to add the new features. Many popular websites like Youtube, Facebook and Twitter expose public data services which we can consume in our web applications. We can merge their data with the data in our application and provide new experiences to the new user. These are the benefits.

These data services are just not only to get the data, we’ve services to modify the data like adding the customer etc. The framework we use to build these data services is called web apis. This framework was developed after ASP.Net MVC but it follows the same architecture and principals of ASP.NET MVC so it has routings, controllers, actions, actionresult and so on. There are also a few minor differences that we’ll see here. In .Net Core, Microsoft has merged these both frameworks (ASP.NET MVC & ASP.NET Web API) into a single framework.

Restful Convention

So you know what  http services and  web api are, here we’ll develop an application which supports  afew different kinds of requests.

GET                               /api/customers                (to get the list of customers)

GET                               /api/customers/1              (to get the single customer)

POST                             /api/ customers               (to add the customer and add the customers data in request body)

Don’t confuse about GET and POST request of the data, we use get request to get the list of the resource or data. And we use post request to create the new one.

Now to update the student we use PUT request.

PUT                               /api/customers/1

So the id of the customer is in the url and the actual data or properties to update will be in the request body. And finally to delete the student.

Delete                             /api/customers/1

We send HttpDelete request to the end point. So what you see here, in terms of request types and endpoints is a standard convention referred to ask REST (Representational State Transfer)

Building An API

This class derives from ApiController as opposed to Controller. If you’re working with any existing project then just add a new folder in controllers folder and add the api controller here, add these actions but before defining the actions in apis, this is my Customer model class

  1. public class Customer  
  2. {  
  3.     public int Id { get; set; }  
  4.    
  5.     [Required]  
  6.     [StringLength(255)]  
  7.     public string Name { get; set; }  
  8.     public bool IsSubscribedToNewsLetter { get; set; }  
  9.    
  10.     [Display(Name = "Date of Birth")]  
  11.     [Min18YearsIfAMember]  
  12.     public DateTime? Birthdate { get; set; }  
  13.    
  14.     // Kamal hogya wese  
  15.     [Display(Name = "Membership Type")]  
  16.     public byte MembershipTypeId { get; set; }  
  17.    
  18.     // it allows us to navigate from 1 type to another  
  19.     public MembershipType MembershipType { get; set; }  
  20. }  

And here is my DbContext class

  1. public class ApplicationDbContext : IdentityDbContext<ApplicationUser>  
  2. {  
  3.     public ApplicationDbContext()  
  4.         : base("DefaultConnection", throwIfV1Schema: false)  
  5.     {  
  6.     }  
  7.    
  8.     public static ApplicationDbContext Create()  
  9.     {  
  10.         return new ApplicationDbContext();  
  11.     }  
  12.    
  13.     public DbSet<Customer> Customers { get; set; }  
  14.     public DbSet<MembershipType> MembershipTypes { get; set; }  
  15. }  

Now it would be easy for you to write actions for Api.

  1. public IEnumerable<Customer> GetCustomers()  
  2. {      
  3. }  

Because we’re returning a list of objects, this action by convention will respond to

  1. // Get          /api/customers  

So this is the convention built into ASP.Net Web API. Now in this action we are going to use our context to get the customers from the database.

  1. namespace MyAPI.Controllers.Api  
  2. {  
  3.     public class CustomersController : ApiController  
  4.     {  
  5.         private readonly ApplicationDbContext _context;  
  6.    
  7.         public CustomersController()  
  8.         {  
  9.             _context = new ApplicationDbContext();  
  10.         }  
  11.    
  12.         // GET /api/customers  
  13.         public IEnumerable<Customer> GetCustomers()  
  14.         {  
  15.             return _context.Customers.ToList();  
  16.         }  
  17.     }  
  18. }  

If the resource isn’t found, we return not found httpresponse otherwise we return the object.

  1. // POST /api/customers  
  2. [HttpPost]  
  3.        public Customer CreateCustomer(Customer customer)  
  4.        {  
  5.              
  6.        }  

So this is the customer argument which will be in the request body and ASP.NET Web API Framework will automatically initialize this. Now we should mark this action with HttpPost because we’re creating the resource. And if we’re following the naming convention then we don’t even need to place the action verb on the action.

  1. // POST /api/customers  
  2. public Customer PostCustomer(Customer customer)  
  3. {  
  4.       
  5. }  

But originally it isn’t a good approach. Let’s suppose you refactor the code in the future and rename your action then surely your code will break. So always prefer to use Http verbs on the top of action.

Now let’s insert the customer object into the database with post request of api action.

  1. // POST /api/customers  
  2. [HttpPost]  
  3. public Customer CreateCustomer(Customer customer)  
  4. {  
  5.     if (!ModelState.IsValid)  
  6.     {  
  7.         throw new HttpResponseException(HttpStatusCode.BadRequest);  
  8.     }  
  9.    
  10.     _context.Customers.Add(customer);  
  11.     _context.SaveChanges();  
  12.    
  13.     return customer;  
  14. }  

Another action --  let’s suppose we want to update the record.

  1. // PUT /api/customers/1  
  2. [HttpPut]  
  3. public void UpdateCustomer(int id, Customer customer)  
  4. {  
  5.     if (!ModelState.IsValid)  
  6.     {  
  7.         throw new HttpResponseException(HttpStatusCode.BadRequest);  
  8.     }  
  9.    
  10.     var custmr = _context.Customers.SingleOrDefault(x => x.Id == id);  
  11.    
  12.     // Might be user sends invalid id.  
  13.     if (custmr == null)  
  14.     {  
  15.         throw new HttpResponseException(HttpStatusCode.NotFound);  
  16.     }  
  17.    
  18.     custmr.Birthdate = customer.Birthdate;  
  19.     custmr.IsSubscribedToNewsLetter = customer.IsSubscribedToNewsLetter;  
  20.     custmr.Name = customer.Name;  
  21.     custmr.MembershipTypeId = customer.MembershipTypeId;  
  22.    
  23.     _context.SaveChanges();  
  24. }  

Here in this scenario, different people have different opinions to return the void or the object.

And if we make the delete action of Api,

  1. // Delete /api/customers/1  
  2. [HttpDelete]  
  3. public void DeleteCustomer(int id)  
  4. {  
  5.     var custmr = _context.Customers.SingleOrDefault(x => x.Id == id);  
  6.    
  7.     // Might be user sends invalid id.  
  8.     if (custmr == null)  
  9.     {  
  10.         throw new HttpResponseException(HttpStatusCode.NotFound);  
  11.     }  
  12.    
  13.     _context.Customers.Remove(custmr);  
  14.     // Now the object is marked as removed in memory  
  15.    
  16.    
  17.     // Now it is done  
  18.     _context.SaveChanges();  
  19. }  

This is how we use restful convention to build the api.

Testing the API

If we run the application and request the api controller, we can see the list of customers in XML based language.

http://localhost:53212/api/customers

ASP.NET

So ASP.NET Web API has what we call media formatter. So what we return from an action (in our case the list of customer will be formatted based on what the client asks) let me explain what I mean and what I’m trying to say.

Inspect the browser on above screen and refresh the page, here you’ll see the customer request.

ASP.NET

Here look at Content Type, if you don’t set the content type header in our request by default the server assumes application/xml.

Note

General is the Request Header, Response Headers is our Response Header here. As you can see in Request Header, we don’t have any content type. Now let me show you the best way to test the api and get the data in json.

Install Postman Desktop App in your machine. And copy the browser link with localhost port number and paste it into the postman.

And here we put the url of the request with localhost and here the response comes back in json

ASP.NET

And if we click on the Header tab, here we’ll see our request header content type is application/json

ASP.NET

Most of the time we’ll be using json because it is native for javascript code and much faster than xml. XML media format is largely used in large organizations like governments because they’re behind the modern technology. Json format is more lightweight because it doesn’t have redundant opening and closing tabs like xml.

Little Confusion

Sometimes when you’re working with Apis or with postman, mostly people confuse about the interface of Postman because they have not ever used postman before. It is very simple just keep in mind,

ASP.NET

So if you’re working with request and trying to change some information of request then focus on request header and if you’re monitoring the response then watch the results in response headers. As they’re looking same and sometimes when the scroll down the request header vanishes. So don’t confuse about the things.

Now let’s insert a customer in the database with Api Post Action.

ASP.NET

Select the Post request from the dropdown and in request body tab. You can insert the customer with key value pairs on clicking form-data. But most of the time we use json format. So click on raw and write the json here.

ASP.NET

Don’t put Id property in json because it is a hard and fast rule when we insert the data in the database, the id is automatically generated on the server.

Now click on Send Button and here I’ve successfully inserted the data with Post api action and it gets the response.

ASP.NET

Here the above block is request block and the below block is response block.

You might face some kind of error here like this.

ASP.NET

If you read the error message ‘The request entity’s media type ‘text/plain’ is not supported for this resource’. This is the error message.

Now to resolve this error. Click on Header tab and add the value for content-type (‘application/json’)

ASP.NET

And here the values has been added. Look the status code for request is 200 OK and we can see the response body below.

Now let’s update the customer entity.

ASP.NET

And look it has been updated.

ASP.NET

Now let’s delete one record similarly, just select Delete in dropdown and specify the id with forward slash in the url and click on Send button. It will be automatically deleted.

Best Practice

The best practice is when you build the api and before consuming it in the application. It would be better to test the api through Postman.

Data Transfer Objects (DTO)

So now we’ve build this api but there are a couple of issues with this design. Our api receives or returns Customer object. Now you might be thinking what’s wrong with this approach? Actually Customer object is part of the domain model of our application. It is considered implementation details which can change frequently as we implement new features in our applications and these changes potentially grab existing clients that are dependent on the customer object; i.e., if we rename or remove our property this can impact the clients that are dependent upon the property. So basically we make the contract of the api as stable as possible. And here we use DTOs.

DTO is the plain data structure and is used to transfer data from the client on server or vice versa that’s why we call it data transfer object. By creating DTOs, we reduce the chances of our APIs breaking as we refactor our domain model. Of course we should remember that changing these DTOs can be costly. So the most important thing is our api should not receive or return the Customer model class object.

Another issue by using domain object here in API is we’re opening the security holes in our application. A hacker can easily pass additional data in json and they will be mapped to our domain object. What if one of these properties should not be updated, a hacker can easily bypass this but if we use DTO we can simply exclude the properties that can be updated. So add a new folder in your project with name DTOs and add the class CustomerDTO and copy all the properties of Customer domain model class with their data annotation attributes and paste it in CustomerDTO. Now remove the navigation properties from CustomerDTO because it is creating the dependency to MembershipType domain model class.

  1. namespace MyAPI.DTOs  
  2. {  
  3.     public class CustomerDTO  
  4.     {  
  5.         public int Id { get; set; }  
  6.    
  7.         [Required]  
  8.         [StringLength(255)]  
  9.         public string Name { get; set; }  
  10.         public bool IsSubscribedToNewsLetter { get; set; }  
  11.    
  12.         [Min18YearsIfAMember]  
  13.         public DateTime? Birthdate { get; set; }  
  14.    
  15.         public byte MembershipTypeId { get; set; }  
  16.     }  
  17. }  

Now the next thing is we want to use to CustomerDTO in our api instead of Customer domain class object. So to reduce a lot of code to bind the properties one by one, we use Automapper.

Automapper

Install the automapper package from Package Manager Console.

PM > Install-Package Automapper -version:4.1

Now add the new class in App_Start (MappingProfile.cs) and inherit it from Profile

  1. using AutoMapper;  
  2.    
  3. namespace MyAPI.App_Start  
  4. {  
  5.     public class MappingProfile : Profile  
  6.     {  
  7.     }  
  8. }  

Now create the constructor and add the mapping configuration between 2 types.

  1. public class MappingProfile : Profile  
  2. {  
  3.     public MappingProfile()  
  4.     {  
  5.         Mapper.CreateMap<Customer, CustomerDTO>();  
  6.         Mapper.CreateMap<CustomerDTO, Customer>();  
  7.     }  
  8. }  

The first argument of the CreateMap is the Source and the second one is destination. When we use the CreateMap method, automapper automatically uses the reflection to scan these types. It finds their properties and maps them based on their names. This is why we called automapper (a convention based mapping tool) because it uses the property names as the convention to map objects. So here is mapping profiles, now we need to load it when the application started.

Now open the Global.asax.cs file and write the code for Application_Start()

  1. protected void Application_Start()  
  2. {  
  3.     Mapper.Initialize(c => c.AddProfile<MappingProfile>());  
  4.     GlobalConfiguration.Configure(WebApiConfig.Register);  
  5.     AreaRegistration.RegisterAllAreas();  
  6.     FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);  
  7.     RouteConfig.RegisterRoutes(RouteTable.Routes);  
  8.     BundleConfig.RegisterBundles(BundleTable.Bundles);  
  9. }  

Now open CustomerController of Api. And let’s start changes here.

  1. // GET /api/customers  
  2. public IEnumerable<CustomerDTO> GetCustomers()  
  3. {  
  4.     return _context.Customers.ToList();  
  5. }  

Now we want to return CustomerDTO type instead of Customer object. Now we need to map this Customer object to CustomerDTO. So we use linq extension method.

  1. // GET /api/customers  
  2. public IEnumerable<CustomerDTO> GetCustomers()  
  3. {  
  4.     return _context.Customers.ToList()  
  5.     .Select(Mapper.Map<Customer, CustomerDTO>);  
  6. }  
  7.   
  8. Mapper.Map<Customer, CustomerDTO>  

This delegate does the mapping. As we can see we’re not placing function call small brackets because we’re not calling the function here. We just reference it here. Mapping function automatically calls, when it executes.

  1. // GET /api/customers/1  
  2. public Customer GetCustomer(int id)  
  3. {  
  4.     var customer = _context.Customers.SingleOrDefault(x => x.Id == id);  
  5.    
  6.     // This is part of the RESTful Convention  
  7.     if (customer == null)  
  8.     {  
  9.         throw new HttpResponseException(HttpStatusCode.NotFound);  
  10.     }  
  11.    
  12.     return customer;  
  13. }  

In this function, as we are returning one object so we don’t use Select extension method. Here we directly use mapper

  1. // GET /api/customers/1  
  2. public CustomerDTO GetCustomer(int id)  
  3. {  
  4.     var customer = _context.Customers.SingleOrDefault(x => x.Id == id);  
  5.    
  6.     // This is part of the RESTful Convention  
  7.     if (customer == null)  
  8.     {  
  9.         throw new HttpResponseException(HttpStatusCode.NotFound);  
  10.     }  
  11.    
  12.     return Mapper.Map<Customer, CustomerDTO>(customer);  
  13. }  

Now come on to the next CreateCustomer action,

  1. // POST /api/customers  
  2. [HttpPost]  
  3. public CustomerDTO CreateCustomer(CustomerDTO customerDto)  
  4. {  
  5.     if (!ModelState.IsValid)  
  6.     {  
  7.         throw new HttpResponseException(HttpStatusCode.BadRequest);  
  8.     }  
  9.    
  10.     var customer = Mapper.Map<CustomerDTO, Customer>(customerDto);  
  11.     _context.Customers.Add(customer);  
  12.     _context.SaveChanges();  
  13.    
  14.     // Here we make our CustomerDto completely fill, because after  
  15.     // adding customer to Customer table (id is assigned to it)  
  16.     // & Now we assigned this id to customerDto  
  17.     customerDto.Id = customer.Id;  
  18.    
  19.     return customerDto;  
  20. }  

This is how we work with Dtos and Automapper.

Now let’s update the UpdateCustomer action api method.

  1. // PUT /api/customers/1  
  2. [HttpPut]  
  3. public void UpdateCustomer(int id, CustomerDTO customerDto)  
  4. {  
  5.     if (!ModelState.IsValid)  
  6.     {  
  7.         throw new HttpResponseException(HttpStatusCode.BadRequest);  
  8.     }  
  9.    
  10.     var custmr = _context.Customers.SingleOrDefault(x => x.Id == id);  
  11.    
  12.     // Might be user sends invalid id.  
  13.     if (custmr == null)  
  14.     {  
  15.         throw new HttpResponseException(HttpStatusCode.NotFound);  
  16.     }  
  17.    
  18.     Mapper.Map<CustomerDTO, Customer>(customerDto, custmr);  
  19.     //custmr.Birthdate = customerDto.Birthdate;  
  20.     //custmr.IsSubscribedToNewsLetter = customerDto.IsSubscribedToNewsLetter;  
  21.     //custmr.Name = customerDto.Name;  
  22.     //custmr.MembershipTypeId = customerDto.MembershipTypeId;  
  23.    
  24.     _context.SaveChanges();  
  25. }  

So this is how we map objects using Automapper. Now automapper has a few features that you may find useful in certain situations; i.e., if your property names don’t match, you can override the default convention or you can exclude some of its properties from mapping or you may want to create custom mapping classes. If you want to learn more, you can learn from Automapper documentation.

IHttpActionResult

Alright look at this CreateCustomer action method

  1. // POST /api/customers  
  2. [HttpPost]  
  3. public CustomerDTO CreateCustomer(CustomerDTO customerDto)  
  4. {  
  5.     if (!ModelState.IsValid)  
  6.     {  
  7.         throw new HttpResponseException(HttpStatusCode.BadRequest);  
  8.     }  
  9.    
  10.     var customer = Mapper.Map<CustomerDTO, Customer>(customerDto);  
  11.     _context.Customers.Add(customer);  
  12.     _context.SaveChanges();  
  13.    
  14.     // Here we make our CustomerDto completely fill, because after  
  15.     // adding customerDto to Customer table (id is assigned to it)  
  16.     // & Now we assigned this id to customerDto  
  17.     customerDto.Id = customer.Id;  
  18.    
  19.     return customerDto;  
  20. }  

Here we’re simply returning CustomerDto which would eventually result in a response like this,

ASP.NET

But in restful convention when we create a resource, the status code should be 201 or created. So we need more control over the response return from an action and to make this happen, instead of returning CustomerDto we return IHttpActionResult. This interface is similar to ActionResult we’ve in MVC framework so it is implemented by few different classes and here in ApiController, we’ve a bunch of methods to create an instance of one of the classes that implement IHttpActionResult interface.

Now here if the model is not valid instead of throwing an exception, use the helper method BadRequest()

  1. // POST /api/customers  
  2. [HttpPost]  
  3. public IHttpActionResult CreateCustomer(CustomerDTO customerDto)  
  4. {  
  5.     if (!ModelState.IsValid)  
  6.         return BadRequest();  
  7.    
  8.     var customer = Mapper.Map<CustomerDTO, Customer>(customerDto);  
  9.     _context.Customers.Add(customer);  
  10.     _context.SaveChanges();  
  11.    
  12.     // Here we make our CustomerDto completely fill, because after  
  13.     // adding customerDto to Customer table (id is assigned to it)  
  14.     // & Now we assigned this id to customerDto  
  15.     customerDto.Id = customer.Id;  
  16.    
  17.     return Created(new Uri(Request.RequestUri + "/" + customer.Id),  
  18.         customerDto);  
  19. }  

As we can see if the ModelState is not valid, it is returning BadRequest and if customer has been added then we return the Uri with this resource id in Created() with the object we’ve finally created the new one.

ASP.NET

Look here we created one more resource and now the status is 201 Created. And if we look the location tab,

ASP.NET

That’s the uri of newly created customer. This is part of the restful convention. So in Web Apis, we prefer to use IHttpActionResult as the returntype of your actions.

Now let’s make changes in the rest of the actions in this Web Api. And here is the complete code of our Api

  1. public class CustomersController : ApiController  
  2. {  
  3.     private readonly ApplicationDbContext _context;  
  4.    
  5.     public CustomersController()  
  6.     {  
  7.         _context = new ApplicationDbContext();  
  8.     }  
  9.    
  10.     // GET /api/customers  
  11.     public IHttpActionResult GetCustomers()  
  12.     {  
  13.         return Ok(_context.Customers.ToList()  
  14.             .Select(Mapper.Map<Customer, CustomerDTO>));  
  15.     }  
  16.    
  17.     // GET /api/customers/1  
  18.     public IHttpActionResult GetCustomer(int id)  
  19.     {  
  20.         var customer = _context.Customers.SingleOrDefault(x => x.Id == id);  
  21.    
  22.         // This is part of the RESTful Convention  
  23.         if (customer == null)  
  24.             return NotFound();  
  25.    
  26.         return Ok(Mapper.Map<Customer, CustomerDTO>(customer));  
  27.     }  
  28.    
  29.     // POST /api/customers  
  30.     [HttpPost]  
  31.     public IHttpActionResult CreateCustomer(CustomerDTO customerDto)  
  32.     {  
  33.         if (!ModelState.IsValid)  
  34.             return BadRequest();  
  35.    
  36.         var customer = Mapper.Map<CustomerDTO, Customer>(customerDto);  
  37.         _context.Customers.Add(customer);  
  38.         _context.SaveChanges();  
  39.    
  40.         // Here we make our CustomerDto completely fill, because after  
  41.         // adding customerDto to Customer table (id is assigned to it)  
  42.         // & Now we assigned this id to customerDto  
  43.         customerDto.Id = customer.Id;  
  44.    
  45.         return Created(new Uri(Request.RequestUri + "/" + customer.Id),  
  46.             customerDto);  
  47.     }  
  48.    
  49. // PUT /api/customers/1  
  50. [HttpPut]  
  51. public IHttpActionResult UpdateCustomer(int id, CustomerDTO customerDto)  
  52. {  
  53.     if (!ModelState.IsValid)  
  54.     {  
  55.         return BadRequest();  
  56.     }  
  57.    
  58.     var custmr = _context.Customers.SingleOrDefault(x => x.Id == id);  
  59.    
  60.     // Might be user sends invalid id.  
  61.     if (custmr == null)  
  62.     {  
  63.         return NotFound();  
  64.     }  
  65.    
  66.     Mapper.Map<CustomerDTO, Customer>(customerDto, custmr);  
  67.    
  68.     _context.SaveChanges();  
  69.     return Ok(custmr);  
  70. }  

Let me mention this point here, as you can see we’ve 2 parameters in UpdateCustomer. If the parameter is primitive type, like we’ve int id, then we’ll place this parameter in route url or with query string. And if we want to initialize our complex type like here we’ve CustomerDTO then we’ll always initialize it from request body in postman. So don’t be confused about this thing here.

  1. // Delete /api/customers/1  
  2. [HttpDelete]  
  3. public IHttpActionResult DeleteCustomer(int id)  
  4. {  
  5.     var custmr = _context.Customers.SingleOrDefault(x => x.Id == id);  
  6.    
  7.     // Might be user sends invalid id.  
  8.     if (custmr == null)  
  9.     {  
  10.         return NotFound();  
  11.     }  
  12.    
  13.     _context.Customers.Remove(custmr);  
  14.     // Now the object is marked as removed in memory  
  15.    
  16.    
  17.     // Now it is done  
  18.     _context.SaveChanges();  
  19.    
  20.     return Ok(custmr);  
  21. }  
  22. }  

Now let’s update and delete the json object through postman. If you focus on the UpdateCustomer action parameter, here the 1st parameter has record id and the 2nd parameter is the Customer domain model class object.

Look it is working with Id in request header because our entity is complete here.

ASP.NET

But if we don’t provide the id in the request header, we’ll get the error.

ASP.NET

And the exceptionMessage is “The property ‘Id’ is part of the object’s key information and cannot be modified.” Actually this exception happens on this line,

  1. Mapper.Map<CustomerDTO, Customer>(customerDto, custmr);  

Because customerDto doesn’t contain the Id but custmr (which is the object variable of Customer model class) has an Id property. And here we need to tell Automapper to ignore Id during mapping to customerDto to custmr. So, come on to the Mapping Profile

  1. public class MappingProfile : Profile  
  2. {  
  3.     public MappingProfile()  
  4.     {  
  5.         Mapper.CreateMap<Customer, CustomerDTO>();  
  6.         Mapper.CreateMap<CustomerDTO, Customer>()  
  7.             .ForMember(c => c.Id, opt => opt.Ignore());  
  8.     }  
  9. }  

And look it is working now,

ASP.NET

Consuming the Web API

After proper testing of the api, now it is the time to consume the api. A most important thing which I would like to mention here is, now our api is ready, you can consume this api in any client. Here we’re showing you the sample of consuming with Visual Studio application. If you’ve built this api with us then you can consume it in php, python, in any framework application with the help of jquery ajax. Now we’ll use jquery to call our api. Look this screen, here I’m showing some customers.

ASP.NET

Now what we want is to delete the row on clicking the delete button. So if you get the idea how we’re rendering the items on the screen, obviously using foreach loop. So on Delete anchor tag click we want record id as well to pass this id to the web api Delete action and on successfully remove the row.

  1. @foreach (var customer in Model)  
  2. {  
  3.     <tr>  
  4.         <td>@Html.ActionLink(customer.Name, "Edit""Customers"new { id = customer.Id }, null)</td>  
  5.         @if (customer.Birthdate != null)  
  6.         {  
  7.             <td>  
  8.                 @customer.Birthdate  
  9.             </td>  
  10.         }  
  11.         else  
  12.         {  
  13.             <td>Not Available</td>  
  14.         }  
  15.         <td>  
  16.             <button data-customer-id="@customer.Id" class="btn btn-link js-delete">Delete</button>  
  17.         </td>  
  18.     </tr>  
  19. }  

This is the html. Now I want to call my api through ajax.

  1. @section scripts{  
  2.     <script>  
  3.         $(document).ready(function() {  
  4.             $('#customers .js-delete').on('click',  
  5.                 function () {  
  6.                     var button = $(this);  
  7.                     if (confirm('Are you sure you want to delete this client?')) {  
  8.                         $.ajax({  
  9.                             url: '/api/customers/' + button.attr('data-customer-id'),  
  10.                             method: 'DELETE',  
  11.                             success: function() {  
  12.                                 button.parents('tr').remove();  
  13.                             }  
  14.                         })  
  15.                     }  
  16.                 });  
  17.         });  
  18.     </script>  
  19. }  

This is how we work with ajax and apis. Now you might be thinking here I’m just passing the id to the customers api and targeting Delete action and on success event I’m removing the row directly. You might think of this scenario in a different way, because every developer has his or her own taste.

You might think that first we delete the record with Delete method and then get all the records from GetCustomers() method of Web Api and then render all these items through each loop of jquery. But this scenario takes too much time and effort. Look when I click on the Delete anchor tag and show the result in inspect browser, the status is 200 ok. It means everything is working fine, our code (Delete action) is working as we expect. So we don’t need to again verify the items we have in the database and render it through each loop.

Just make your scenario simple, and remove the record as I do here.

Conclusion

So the conclusion is always follow the Restful convention when you’re working with Web Apis. Web Apis are more lightweight than SOAP based web services. They are cross platform. Restful Http verbs helps in the application a lot to insert, delete, update, get the records. Here we see how we use the postman and there are 2 different panes like request header and response header. Most of the time developers get confused about how to use Web Api actions with jquery ajax. Here we also consume the action as well.


Similar Articles