In this tutorial, we will learn what is Web API and the step by step demonstration of a simple Web API project in ASP.NET. Along we will learn about the Postman tool also.
Web API
A Web API is an application programming interface for either a web
server or a web browser.
In simple word, we can say it is a Service which is created once and can be used in any devices to access data or features. It is lightweight so it can reach to low bandwidth devices like Tablet and Mobile. The responses can be formatted as JSON, BSON, XML, etc through Web API Media Type Formatter.
Uses of Web API
· ASP.NET Web API is an ideal platform for building RESTful
services.
· ASP.NET Web API is built on top of ASP.NET and supports ASP.NET
request/response pipeline
· ASP.NET Web API maps HTTP verbs to method names.
· ASP.NET Web API supports different formats of response data.
Built-in support for JSON, XML, BSON format.
· ASP.NET Web API can be hosted in IIS, Self-hosted, or any other web hosting server that supports .NET 4.0+.
· ASP.NET Web API framework includes new HttpClient to communicate
with the Web API server. HttpClient can be used in ASP.MVC server side, Windows
Form application, Console application, or other apps.
Create ASP.NET Web Application in Visual Studio
Open Visual Studio 2019 and open a new
project. Select ASP.NET Web Application(.Net Framework).
Give the project name and click Create.
Select Web API in the template window. After
selecting Web API, we can see on the right side in the "Add folders & code references" section MVC and WEB API are selected automatically as shown in the below figure.
So we can develop both Mvc And Api projects together.
To develop only Web API project, we have to select an Empty Template and check only the Web API option like
below.
Over View of Project Files
After the project is created you can see this
interface. The project architecture is same as the MVC project. We have the same Model , controller, App_Start folders etc..we don't have View folder, because we are not going for showing any GUI in API Services. Have a look on the App_Start folder.
API Configuration
Open App_Start -> WebApiConfig.cs
You can see below code on the WebApiConfig.cs file
Here the routing is defined for our API ,instead we can change it.
public static void Register(HttpConfiguration config)
{
// Web API
configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id =
RouteParameter.Optional }
);
}
In the above code the routing for our API call will be like "api/{controller}/{id}"
Ex:- here is a controller HomeController, I have 2 methods method1(),method2(int id).
public class HomeController: ApiController
{
[HttpGet]
public string method1()
{
}
[HttpGet]
public string method2(int id)
{
}
}
for the above method1() call we have to write the API route as "api/Home"
and for the method2(int id) call we have to write the API route as "api/Home/1001"
But for the same request we can not define multiple actions, so to overcome this we can change our routing to "api/{controller}/{action}/{id}" like this.
Ex:- here is a controller HomeController, I have 2 methods method1(),method2(int id) and methods().
public class HomeController: ApiController
{
[HttpGet]
public string method1()
{
}
[HttpGet]
public string method2(int id)
{
}
[HttpGet]
public string method3()
{
}
}
requests for actions will be like below
method1() call :-"api/Home/method1"
method2(int id) call :-"api/Home/method1/1001"
method2(int id) call :-"api/Home/method3"
Note:- we have to configure the Register method [public static void Register(...)] in the Global.asax file.as given below. It is by default configured while creating the project.
Adding a Controller
Now, go to Controller and expand the
controller folder. We need to create a new API controller, we can create that
in the following way.
Select and right-click on Controllers Folder -> Add -> Controller.
Select Web API 2 Controller-Empty.
Rename control name as HomeController.
Adding a Method in Controller
Now, create a simple method in Controller,
build the application, and run it finally. In web API, we use the method name
as View()We can use any other method
name. Let's write the below code in the HomeController.
public class HomeController :
ApiController
{
[HttpGet]
publicstring View()
{
return "My
first Web Api";
}
}
Run
Web API
We
have to run the Web API api/Controller/Method
URL format. For example, in MVC we define URL format using “RouteConfig” class
and “RegisterRoutes” static methods. The same for Web API also; we are using the
“WebApiConfig” and “Register” static method.
Go to the “Global.aspx” file we
can see in detail. We see it before in this tutorial.
Now Run the project: http://localhost:55410/api/home/view
Web API has returned a
result in XML or JSON format. Our output will look like above.
To test the API calls we have so many tools are available like Postman, Swagger, feeder, etc. Here we will know about Postman.
Postman
Postman is
a software tool. It enables people to test calls to APIs.
Installing the Postman API client
- Download the Postman API Client from
the Postman
website (https://www.getpostman.com/product/api-client).
- Double-click the downloaded installer and
follow prompts.
- Once the installer finishes, launch the application by clicking the Postman icon.
- Once the application starts for the first time, users will be presented with a login window.
- Have a Postman account? Enter your
Postman username and password.
- Have a Google account for university use? Click the "Sign in with Google" button and follow prompts.
Do not use a personal Google account.
- Avoid signing in by clicking the
"Skip signing in" link at the bottom of the window.
copy the browser URL of our API i.e. http://localhost:55410/api/home/view
paste it in the text box as shown below. Make sure the left dropdown is GET(i.e. it is a GET method). Click Send.
Note:- Do not close the running project in the background.
You can see the result as shown below.