Introduction
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 eventually share the data
across. The most popularly used method types are GET & POST.
Today,
I shall be demonstrating the creation of REST Web API GET type method with
or without parameters using the ASP.NET REST Web API platform.
Prerequisites
Following are some prerequisites before you proceed any further in this tutorial:
- Knowledge of REST Web API
- Knowledge of ASP.NET MVC5.
- Knowledge of C# Programming.
The example code is
being developed in Microsoft Visual Studio 2019 Professional. The sample sales data are taken randomly from the internet.
Let's begin now.
Step 1
Create a new Web API project and name it "RESTWebApiGetMethod".
Step 2
Create "Controllers\WebApiController.cs" file.
Step 3
Create "Get" method without parameter inside "Controllers\WebApiController.cs" file and replace following code in it i.e.
- ...
- public HttpResponseMessage Get()
- {
-
- HttpResponseMessage response = null;
- DataTable responseObj = new DataTable();
- string json = string.Empty;
- ...
-
-
-
- ...
-
- json = JsonConvert.SerializeObject(responseObj);
- response = Request.CreateResponse(HttpStatusCode.OK);
- response.Content = new StringContent(json, Encoding.UTF8, "application/json");
- ...
-
-
- 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 a 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 required data
without any query filtration and finally, prepare & send the
response JSON packet. There are a few things in the above code that need
to be taken care of, i.e.
- The first point is the 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 is "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 the 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 a prefix with your method name.
- 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 the above method, all you need to do
is to use: 'https://localhost:44334/api/WebApi/' URL and you will get your result.
- 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.
Step 4
Create a "Get" method with a parameter inside "Controllers\WebApiController.cs" file and replace the following code in it, i.e.
- ...
- public HttpResponseMessage Get(string salesChannel, string priority)
- {
-
- HttpResponseMessage response = null;
- DataTable responseObj = new DataTable();
- string json = string.Empty;
-
- ...
-
-
-
- ...
-
- json = JsonConvert.SerializeObject(responseObj);
- response = Request.CreateResponse(HttpStatusCode.OK);
- response.Content = new StringContent(json, Encoding.UTF8, "application/json");
- ...
-
- return response;
- }
- ...
Although it is not recommended to use the GET
type method for input request data, if your request parameter is
not complex and only one or two parameters, then you can utilize those
parameters into the GET type method. 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.
- 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 the GET type method, you can only accept request parameters via URL. However, the response can be of JSON type. In the above code, my method is receiving input request
parameters in the method signature. To call a 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 the default GET type
method with parameters, otherwise you will either get error or default
GET method result. You can utilize the Method Name Routing technique to achieve your target name. Follow the convention and
use post/get as a 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. The 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 }
- );
- ...
- 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.
Step 5
Let's test out the REST Web API in action using the REST Web API client. I am using the 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 the 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 learned to create REST Web API
GET type method with or without parameters using the ASP.NET REST Web API
platform. You also learned about default behavior that ASP.NET MVC
platform offers with respect to creating POST/GET type methods. You learned about creating GET type method with input request parameter i.e.
either via URL parameter. You learned about two input request URL
parameter formats for the GET type method and how to configure them
according to your needs. You also learned to properly create a response
packet with proper string formatting and finally, you learned to test
REST Web API using any REST client to see your REST Web API in action
before consumption.