Create Restful APIs by using ASP.Net Web API 2

ASP.NET Web API is a framework for building HTTP services that can be accessed from any client including browsers and mobile devices. It is an ideal platform for building RESTful applications on the .NET Framework. However it can also use to create non RESTful services.
It works more or less the same way as ASP.NET MVC web application except that it sends data as a response instead of html view.
ASP.Net web API became very popular because of it’s a very easy to implement RESTful api with less amount of time. Through this series we will learn how to handle Http Methods, Content Negotiation, Media Type Formatters, Authentication, and Versioning of API.
Along with this we will also see how to send request from jQuery Ajax and a postman app.

Offer: If you are interested to learn more about ASP.Net Web API 2 then you can visit my video series on Udemy.

Create Web API
Start visual studio and open File > New Project > Installed Template > ASP.Net Web Application > OK > Select MVC > OK
Create a new Empty controller which will contains all actions provided by API.
ASP.Net Web API

Retrieve All book details
I am already created Context by using Entity Framework. We can use HttpGet, HttpPost, HttpPut, HttpDelete attributes. If our method name is start with Get, Put, Post, Delete then we does not need to specify that attribute. In below method i am not start with Get so i need to use HttpGet attribute. to return all data just created instance of Entity context and from which retrive all products as list and return it.

[HttpGet]
public IEnumerable<Product> LoadAllProducts()
{
    using (ProductEntities entity = new ProductEntities())
    {
        return entity.Products.ToList();
    }
}

Retrieve book of specific Id
Here, we will obtain Id from a parameter, and use Lambda expression with Entity framework to obtain only Product with this id.
If book with this id does not exist then it will return null, so if we got null then return Not found message. And if found then return Product object itself.
Here, we are returning HttpResponseMessage which contains HttpStausCode and data that we want to return, and any data that we really want to pass to browser.

public HttpResponseMessage Get(int id)
{
    using (ProductEntities context = new ProductEntities())
    {
        Product product = context.Products.FirstOrDefault(x => x.ProductId == id);
        if (product == null)
            return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Product with given Id does not exist!");
        return Request.CreateResponse(HttpStatusCode.OK, product);
    }
}

Add Data into Database
To add product details we need to pass all of the parameters of that class in query string. Add object by using Entity Framework. After adding object we also need to set Location in response which specify an URL where newly added Product can access.

[AcceptVerbs("GET", "POST")]
public HttpResponseMessage Post(Product product)
{
    try
    {
        using (ProductEntities context = new ProductEntities())
        {
            context.Products.Add(product);
            context.SaveChanges();

            HttpResponseMessage message = Request.CreateResponse(HttpStatusCode.Created, product);
            message.Headers.Location = new Uri(Request.RequestUri + product.ProductId.ToString());
            return message;
        }
    }
    catch (Exception ex)
    {
        return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
    }
}

Update Data
To update data we need to pass id of Product that we want to update and Product object which contains new data. We can pass data in Web API in 2 ways via Body or Query string. if we are passed via query string then we need to use FromUri attribute, and for body we need to use FromBody attribute.

public HttpResponseMessage Put([FromUri]int id, [FromBody]Product newProduct)
{
    try
    {
        using (ProductEntities context = new ProductEntities())
        {
            Product existingProduct = context.Products.FirstOrDefault(x => x.ProductId == id);
            if (existingProduct == null)
                return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Product with Given Id does not exist!");

            existingProduct.Name = newProduct.Name;
            existingProduct.Price = newProduct.Price;
            existingProduct.Quantity = newProduct.Quantity;
            existingProduct.BoxSize = newProduct.BoxSize;
            context.SaveChanges();
            return Request.CreateResponse(HttpStatusCode.OK, existingProduct);
        }
    }
    catch (Exception ex)
    {
        return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
    }
}

Delete Data
To delete we need to pass id in query string, before deleting data we need to check Product details for that id is exist or not.

public HttpResponseMessage Delete(int id)
{
    using (ProductEntities context = new ProductEntities())
    {
        Product product = context.Products.FirstOrDefault(x => x.ProductId == id);
        if (product == null)
            return Request.CreateResponse(HttpStatusCode.NotFound, "Product with Given Id does not exist!");

        context.Products.Remove(product);
        context.SaveChanges();
        return Request.CreateResponse(HttpStatusCode.OK);
    }
}

Offer: If you are interested to learn more about ASP.Net Web API 2 then you can visit my video series on Udemy.

Leave a Reply

Your email address will not be published. Required fields are marked *