All About API: HTTP Response Message

All About API: HTTP Response Message

In this article we will see HTTP Response Message as return type for the API method. This is part three of the article series. Before reading this article, I would recommend reading the following previous parts.

HTTPResponseMessage feature is provided by WebAPI framework which is used to create HTTP services. It helps us to send responses in different ways. HTTPResponse message is used to return data as well as some user friendly messages like:

Status CodeStatus Message
200OK
201Created
404Not Found

HTTPResponseMessage in Web API

Now let’s see step by step implementation of HTTPResponseMessage:

  • Open Visual Studio Editor

  • Select ‘File’ menu, expand ‘New’ and click on ‘Project…’

image.png

  • Expand ‘Visual C#’ and select ‘Web’ from the left panel
  • Select ‘ASP.NET Web Application’
  • Provide appropriate name of the application and select the location
  • Click on ‘OK’ button,

image.png

  • Select ‘Empty’ as a template and check ‘Web API’ check box
  • Press ‘OK’ button and it will create an empty Web API project.

image.png

  • Right click on ‘Controllers’, expand ‘Add’ and click on ‘Controller…’

image.png

  • Select ‘Web API 2 Controller with read/write actions’ and press ‘Add’ button, which will add all HTTP methods.

image.png

  • Provide appropriate name and press ‘Add’ button,

image.png

  • Controller is created with read / write actions,

    namespace HTTPResponseMessage.Controllers  
    {  
        public class ServiceController: ApiController  
        {  
            // GET: api/Service  
            public IEnumerable < string > Get()  
            {  
                    return new string[]   
                    {  
                        "value1",  
                        "value2"  
                    };  
                }  
                // GET: api/Service/5  
            public string Get(int id)   
                {  
                    return "value";  
                }  
                // POST: api/Service  
            public void Post([FromBody] string value) {}  
                // PUT: api/Service/5  
            public void Put(int id, [FromBody] string value) {}  
                // DELETE: api/Service/5  
            public void Delete(int id) {}  
        }  
    }
  • Set HttpResponseMessage as return type for all API methods.

  • Here we are using Request.CreateErrorResponse to create an HttpResponseMessage.

namespace HTTPResponseMessage.Controllers  
{  
    public class ServiceController: ApiController  
    {  
        static List < string > serviceData = LoadService();  
        public static List < string > LoadService()   
        {  
                return new List < string > ()   
                {  
                    "Mobile Recharge",  
                    "Bill Payment"  
                };  
            }  
            // GET: api/Service  
        public HttpResponseMessage Get()   
            {  
                return Request.CreateResponse < IEnumerable < string >> (HttpStatusCode.OK, serviceData);  
            }  
            // GET: api/Service/5  
        public HttpResponseMessage Get(int id)   
            {  
                if (serviceData.Count > id) return Request.CreateResponse < string > (HttpStatusCode.OK, serviceData[id]);  
                else return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Item Not Found");  
            }  
            // POST: api/Service  
        public HttpResponseMessage Post([FromBody] string value)   
            {  
                serviceData.Add(value);  
                return Request.CreateResponse(HttpStatusCode.Created, "Item Added Successfully");  
            }  
            // PUT: api/Service/5  
        public HttpResponseMessage Put(int id, [FromBody] string value)   
            {  
                    serviceData[id] = value;  
                return Request.CreateResponse(HttpStatusCode.OK, "Item Updated Successfully");  
            }  
            // DELETE: api/Service/5  
        public HttpResponseMessage Delete(int id)   
            {  
            serviceData.RemoveAt(id);  
            return Request.CreateResponse(HttpStatusCode.OK, "Item Deleted Successfully");  
        }  
    }  
}

Run your application and follow below steps:

GET

  • Select ‘GET’ as Method
  • Copy URL and press ‘SEND’ button
  • In the response header, you can see the http status code and message ‘200 OK’
  • Observe the response, we can see two string elements are added in the list.

image.png

GET By ID

  • In order to get the individual string element from the list, pass index in the URL
  • In the response header, you can see the http status code and message ‘200 OK’
  • Check the response, you will have individual element associated with the index.

image.png

POST

  • Select ‘POST’ as method
  • Add Content-Type header with the value ‘application/json’
  • Add the value which you want to add in the list in Body and press ‘SEND’ button
  • In the response header, you can see the http status code and message ‘201 Created’

image.png

PUT

  • Select ‘PUT’ as method and add index for which you want to modify in the URL
  • Add Content-Type header with value ‘application/json’
  • Add updated value in the body and press ‘SEND’ button
  • In the response header, you can see the http status code and message ‘200 OK’

image.png

DELETE

  • Select ‘DELETE’ as method and add index for which you want to delete from the list in URL
  • Press ‘SEND’ button
  • In the response header, you can see the http status code and message ‘200 OK’.

image.png

Next >> All About API: HTTP Verb Attributes - Part Four