Header Ads

ASP.NET MVC: REST Web API GET Method

REST Web API is the most vital component for sharing data across multiple devices e.g. mobile devices, desktop applications or any website. The key element in developing & designing REST web API is to identify the type of methods that will eventual share the data across. The most popularly used method types are GET & POST.
Today, I shall be demonstrating creation of REST Web API GET type method with or without parameters using ASP.NET REST Web API platform.



Prerequisites:

Following are some prerequisites before you proceed any further in this tutorial:
  1. Knowledge of REST Web API.
  2. Knowledge of ASP.NET MVC5.
  3. Knowledge of C# Programming.
The example code is being developed in Microsoft Visual Studio 2019 Professional.The sample sales data is taken randomly from the internet.

Download Now!

Let's begin now.

1) Create new Web API project and name it "RESTWebApiGetMethod".  
2) Create "Controllers\WebApiController.cs" file.
3) Create "Get" method without parameter inside "Controllers\WebApiController.cs" file and replace following code in it i.e.

...
        public HttpResponseMessage Get()
        {
            // Initialization
            HttpResponseMessage response = null;
            DataTable responseObj = new DataTable();
            string json = string.Empty;
...

            // Loading Data.
            // do smething.
...
            // Settings.
            json = JsonConvert.SerializeObject(responseObj);
            response = Request.CreateResponse(HttpStatusCode.OK);
            response.Content = new StringContent(json, Encoding.UTF8, "application/json");
...

            // Info.
            return response;
        }
...

In the above code, a simple Get method with no parameter has been created, know that this will be the default method which will be called when 'https://localhost:44334/api/WebApi/' url is hit either using REST API client or via browser. Since, I am not using authorization for REST Web API, so, JSON result can also be visualized in any browser as well. The above method will load the require data without any query filtration and finally, prepare & send the response JSON packet. There are few things in the above code that need to be taken care off i.e.
  1. The first point is name of our target POST/GET type method, know that in ASP.NET MVC platform, the advantage of writing REST Web API is that the platform takes care of most of the things, the default names by convention in ASP.NET MVC REST Web API platform are "Get" for GET type method with method overloading with parameter variations and "Post" for POST type method, this is the reason developers do not explicitly need to write "HttpPost" data annotation/Attribute tag above GET type method to explicitly tells the platform that it is GET type method. However, if you need to change the default name of post/get method or you have more complex number of methods then you can utilize Method Name Routing technique to achieve your target name, but, follow the convention and use post/get as prefix with your method name.

  2. In the second point, you need to understand that since, ASP.NET MVC REST WEB API platform suffices the default behavior of the method names, therefore, you do not need to explicitly write method name in your REST Web API Client. For example, to access above method, all you need to do is to use 'https://localhost:44334/api/WebApi/' URL and you will get your result.

  3.  In the third and final point, you need to explicitly create your response packet to return JSON resultant data otherwise your direct JSON response might have slashes and improper string formatting causing difficult for your consumer application to consume the REST Web API.
4) Create "Get" method with parameter inside "Controllers\WebApiController.cs" file and replace following code in it i.e.

...
        public HttpResponseMessage Get(string salesChannel, string priority)
        {
            // Initialization
            HttpResponseMessage response = null;
            DataTable responseObj = new DataTable();
            string json = string.Empty;

...
            // Loading Data.

            // Processing Query.
...
            // Settings.
            json = JsonConvert.SerializeObject(responseObj);
            response = Request.CreateResponse(HttpStatusCode.OK);
            response.Content = new StringContent(json, Encoding.UTF8, "application/json");
...
            // Info.
            return response;
        }
...

Although, it is not recommended to use GET type method for input request data, but, if your request parameter is not complex and one or two parameter then you can utilize those parameters into GET type method, but, do make sure that your query parameters are not sensitive data. So, in the above code, a simple Get method with parameters have been created. Since, I am not using authorization for REST Web API, so, JSON result can also be visualized in any browser as well. The above method will load the require data with request query filtration and finally, prepare & send the response JSON packet. There are few things in the above code that need to be taken care off i.e.
  1. In the first point, you need to understand that how you want to send your input query data i.e. via URL parameters or via JSON. In the above code for GET type method, you can only accept  request parameters via URL. However, response can be of type JSON. In the above code, my method is receiving input request parameters in the method signature. To call GET type method with parameters, you need to send parameters into URL like 'https://localhost:44334/api/WebApi?salesChannel=online&priority=M', this is the standard way of sending request data via URL parameters. If however, you want to use 'https://localhost:44334/api/WebApi?online/M' URL to send data to the GET type REST Web API method then you need to configure 'App_Start\WebApiConfig.cs' file with API default URL parameters, since, this is default GET type method with parameters, otherwise you will either get error or default GET method result. You can utilize Method Name Routing technique to achieve your target name, but, follow the convention and use post/get as prefix with your method name and know that it will only receive input request parameters in '?&' format or you can configure 'App_Start\WebApiConfig.cs' file with non-default API routing to use other format. Following line of code in 'App_Start\WebApiConfig.cs' file will enable 'https://localhost:44334/api/WebApi?online/M' URL format.

    ...
                config.Routes.MapHttpRoute(
                    name: "DefaultApi",
                    routeTemplate: "api/{controller}/{salesChannel}/{priority}",
                    defaults: new { salesChannel = RouteParameter.Optional, priority = RouteParameter.Optional }
                );
    ...
    

  2. In the second and final point, you need to explicitly create your response packet to return JSON resultant data otherwise your direct JSON response might have slashes and improper string formatting causing difficult for your consumer application to consume the REST Web API.
5) Lets, test out REST Web API in action using REST Web API client. I am using Firefox plugin i.e. "RESTED". Execute the project and simply hit the REST Web API via URL directly as the REST Web API does not have any authorization, I will get following response i.e.


Try 'https://localhost:44334/api/WebApi' URL i.e.



Try 'https://localhost:44334/api/WebApi?salesChannel=online&priority=M' and 'https://localhost:44334/api/WebApi?online/M' URL(s) i.e.


Conclusion

In this article, you will learn to create REST Web API GET type method with or without parameters using ASP.NET REST Web API platform. You will also learn about default behavior that ASP.NET MVC platform offers in respect to creating POST/GET type methods. You will learn about creating GET type method with input request parameter i.e. either via URL parameter. You will learn about two input request URL parameters formats for GET type method and how to configure them according to your need. You will also learn to properly create response packet with proper string formatting and finally, you will learn to test REST Web API using any REST client to see your REST Web API in action before consumption.

No comments