ASP.NET Web API TutorialIn this tutorial, we will discuss the following topics: ASP.NET Web API tutorial provides basic and advanced concepts of ASP.NET. Our ASP.NET tutorial is designed for beginners and professionals both. What is Web API?- Web API is the enhanced form of the web application to provide services on different devices like laptop, mobile, and others.
- Today, all kind of businesses use the internet as a cost-effective way to expand their business in the international market.
- Web application helps to exchange information on the internet and also helps to perform a secure transaction on web sites.
- Web applications are popular as the web browser is available in default, we don't need any installation of software on computers with operating systems.
- For example, Facebook (a social networking web application), Flickr (a photo-sharing web application), and Wikipedia are majorly used example of a web application.
- Technically, a web application consists of two types of scripts:
1) Client-side scripts: JavaScript, HTML, and other client-side scripting languages are used to design the web forms to present information to users. 2) Server-side scripts: ASP and other server-side scripting languages are used to perform business logic and database related operations like storing and retrieving information. - A web application is Human-System interaction.
- Either it can be single page application just to provide information for some business, or it can be a collection of web pages that are used to take some information from the user and providing the services to the user.
Who uses API?These services can be accessed by different kind of users like: - Web Browsers
- Mobile applications
- Desktop applications
- IOTs (Internet of Things)
ASP.NET Web APIAPI stands for the Application Programming Interface. "ASP.NET Web API is an extensible framework for building HTTP (Hypertext Transfer Protocol) services that can be accessed from any client such as browsers and mobile devices." For example, we make a reservation from different web applications like MakeMyTrip, Ixigo or Paytm and all other reservation web applications, but all applications make a reservation using credentials from IRCTC web site only, i.e., user performing reservation must have login credentials of IRCTC web site. These services can be accessed by different kind of users like: - Web Browsers
- Mobile applications
- Desktop applications
- IOTs (Internet of Things)
Web API services are used when the application is to be used on a distributed system. Web API takes requests from the different type of client devices like mobile, laptop, etc. and sends them to the web-server to process it and returns the desired data to the client. Custom Web Application using a different kind of API's Web API is System-System interaction, where information from one system is processed by another system, and resultant data is shown to the viewer. Let's take another example from Web API examples, we want McDonald's burger. Let us suppose McDonald's only gives permission for takeaways to cooks only and not for others. Here McDonalds-Takeaways (cook) is like an API, which allows other systems (cooks) to access the services and provide desired data.
ASP.NET Web API features1) ASP.NET Web API is much similar to ASP.NET MVC. 2) It contains similar features as ASP.NET MVC like: - Routing
- Controllers
- Action results
- Filter
- Model, etc.
3) There is a misconception that ASP.NET Web API is a part of ASP.NET MVC framework, while it can be used with any other type of web application. 4) Stand-alone services can be developed using the Web API. 5) ASP.NET Web API framework is widely used to develop RESTful services.
RESTful services- Web API is the enhanced form of a web application.
- SOAP (Simple Object Access Protocol) was an XML based protocol for developing the connected web applications.
- Problem with the SOAP was that with each request, Metadata is attached with data to be transferred.
- This Metadata converts small data to heavy data on the server.
- Web API may or may not be RESTful services, but they are always HTTP based services.
- REST stands for Representational State Transfer.
- In REST API, only the state of the object is sent to the server to find the desired result.
- REST is an architectural pattern for developing an API that uses HTTP as its underlying communication method.
When we are using HTTP based service, for example, BookMyShow app, we need data in managed form like JSON format, XML format. Client requests for the information by sending parameters using API methods. For example, if we want to book a show for which we want to know the details like City, Movie Name, Place, Timing. We will send the state of the object to the web-server, and API will check whether the data is available or not. If the data is available (the movie is available for that instance), then it will send back the response to the client with the object. Values of an object are sent to the client, i.e., basically state of an object is sent to the client, so each time you don't have to create an object. "REST API is an architectural style as well as an approach for communications purpose that is often used in various web developments." It is a stateless, client-server model.
Principles of REST APIThe six principles of REST API are: - Stateless
- Client-Server
- Uniform Interface
- Cacheable
- Layered System
- Code on demand
1) Stateless: When the request from the client is sent to the server, it contains all the required information to make the server process it. A request may be part of QueryString or URL. For example, let's suppose the resource is requested from the URL (Uniform Resource Locator). 2) Client-Server: Separating the functionality helps to increase user interface portability across multiple platforms as well as extended the scalability of the server components. 3) Uniform Interface: To obtain the uniformity throughout the application, REST has defined four interface constraints for which are: - Resource Identification
- Resource Manipulation using representations
- Self-descriptive massages
- And hypermedia as the engine of the web application
4) Cacheable: In order to provide a better performance, applications are made cacheable. It is done by marking the response as cacheable or non-cacheable implicitly or explicitly. If the resource is defined cacheable, then the client cache can reuse response data for equivalence requests. 5) Layered System: The layered system allows an application to be most stable by limiting component behavior. The layered architecture also helps to enhance security as the component at each layer cannot interact beyond each layer they are in. 6) Code on demand: Constraint that is used optionally and least. Analyze and simplify the client by creating a smart application which doesn't lie on its own code structure.
Methods of REST API- Working on web technologies, we work on CRUD applications.
- In these applications, CRUD is to CREATE, READ, UPDATE, and DELETE a resource.
- Here, a resource is defined as the desired result. For example: https://in.bookmyshow.com/noida/movies
- In the above example, the user is looking for movies in city Noida on bookmyshow application, so the resource is the data, the client is looking for.
- To perform these actions like to create a resource, read a resource, update a resource, or delete a resource, we can use HTTP methods also called as REST methods.
Now the basic CRUD operations are mapped to the HTTP protocols in the following manner: CRUD Methods | REST API Methods | Description |
---|
Create | POST | Method refers to the C(Create) part of the CRUD. It is used to create a resource. | Read | GET | Method refers to the R(Retrieve) part of the CRUD. It is used to read a resource. | Update | PUT | Method refers to the U(Update) part of the CRUD. It is used to update a resource. | Delete | DELETE | Method refers to the D(Delete) part of the CRUD. It is used to delete a resource. |
- REST API is best used for distributed systems.
- A distributed database is used everywhere, database stores data, on which CRUD (Create, Retrieve, Update, and Delete) operations are performed.
So let's have an example of getting some dishes from the resource: www.testwebsite.com/dishes Now let's assume we want some specific dish from resource: www.testwebsite.com/dishes/2
Implementing REST API Simple applicationLet's create a REST API service for students. - Firstly open Visual Studio (here we have Visual Studio 2019).
- Now select Create a new project:
- Now select the template ASP.NET Web Application (.NET Framework) with C# and name the project as "WebApiStudentsSample".
- In the ASP.NET Project dialog, select the Empty template and also check Web API option. Click OK.
- A default structure generated will be as follows:
Adding Student.cs class to the Models folder - Add a class with the name "Student" to define properties and other business logic. We can also define other logics as validation, data access, etc.
- Right-click on Models, Select Add option, and then select Class and give a name to the class as "Student.cs"
Add the following code to define properties for student class: Adding StudentControllers.cs class to Controllers folder - Controller class handles HTTP request from the client, which may be a desktop application, mobile device, and browser.
- Right-click on Controllers, Select Add option, and then select 'Controller..'.
Add Scaffold window will open then Select Web API2 Controller ?Empty template. - After selecting Scaffolding template, Add controller window will open and give a name to the class as "StudentController".
Note: We can see that the controller class inherits the System.Web.Http.ApiController class instead of the Controller class.- Scaffolding creates a "StudentController.cs" class inside the controller folder.
Now implement methods to perform CRUD operations. Let us assume we want all student details and also details for some specific student. Now add following code: In the StudentController class controller, you can see that the method "GetAllStudents" return the list of all students and the method "GetStudentDetails" returns the detail of single student. In the following table, you can understand how controller use route URL to perform CRUD action. Controller Method | Route URI(Uniform Resource Identifier) | GetAllStudents | /api/ student | GetStudentDetails | /api/ student /id |
Run The Web API To run a Web API, firstly press F5 or Ctrl+F5 or Click on IIS express run icon then the browser will open with the URL like https://localhost:44329/ Now to find the list of all students edit the URL as https://localhost:44329/api/student To fetch the details of a single student, Edit the URL as: https://localhost:44329/api/student/2
Need for Web API- A Web API helps to access service data from different internet devices like browsers, mobile apps, and other devices.
- Helps to work on RESTful web services.
- Helps to develop light weighted and maintainable Web Services.
- Used to create both types of services RESTful and non-RESTful services.
- Also supports JSON, XML, and other data formats.
- Helps to develop services supporting all features of HTTP services such as like caching, request/response headers, versioning, etc.
MVC vs. Web APIDifferences between ASP.NET API and ASP.NET MVC are as follows: MVC | Web API |
---|
Helps to develop web applications that process the request and sends both views and data. | Helps to develop HTTP services (RESTful and non-RESTful services) that process the request and returns data only, not a view. | Represents resultant data in JSON format using JsonResult. | Return data in particular format like JSON, XML or any other format | A request is mapped to actions name. | A request is mapped to HTTP verbs in Web API | Model binding, routing, and other features are defined in System.Web.Mvc. | Same features are available in Web API, and these features are defined in System.Web.Http assembly. | MVC usually interact with the views to provide final output | Supports feature of content-negotiation, i.e., deciding the best format for response data that is compatible with the client machine. |
Web API vs. WCFDifferences between ASP.NET WCF and ASP.NET Web API are as follows: Feature | Web API | WCF |
---|
Content format | Web API supports any media format like XML, JSON, etc. | WCF supports SOAP-based services and XML format. | Hosting | Web API supports IIS hosting, Self-hosting | WCF supports works activation services and also IIS hosting, Self-hosting. | MVC features | ASP.NET Web API supports features like controllers, routing, action, etc. same as MVC. | Like MVC, WCF does not provide any features like controllers, routing, filter, auction results, etc. | Protocol | Web API supports HTTP protocol. | UDP, HTTP, and custom transport protocol are supported. | Use of model | Uses HTTP verbs as methods called as CRUD operations | ServiceContract attribute defines a Service Contract that contains operations. OperationContract attribute defines the operations that will be used. DataContract attribute defines the properties or types that will be transferred between the parties. |
Web API vs. Web ServicesDifferences between Web API and Web services are as follows: Features | Web API | Web services |
---|
Hosting | Hosting is done within an application or IIS. | Hosting is done on IIS. | Open Source | Web API is open-source, and it can be used by any client that supports JSON or XML. | Web service is not open-source but can be used by any client that supports XML. | Architecture | Web API is light-weighted architecture and good for devices which have limited bandwidth, like mobile devices. | It requires a SOAP protocol to receive and send data over the network, so it is not light-weight architecture. | Protocol | It supports the HTTP protocol: URL, Request/Response Headers, versioning, caching, content formats. | It supports the HTTP protocol only. |
Web API SecurityASP.NET Web API Authentication and Authorization are important concepts for Web API security. Suppose a web API is created, and the access to the API is for some specific users, and also different operations are available for different users. - Authentication is to validate the credentials for the user and identify them.
For example, a user login with his username and password and server authenticate the user by a password. - Authorization is to define the access level for each user to perform a different operation.
For example, a person is allowed to create a resource but not to delete the record.
If a request requires authentication in web API, but the client does not provide the credentials in the request header, then the server will return 401 (Unauthorized).
PrerequisiteBefore learning Web API, the user must have basic knowledge of Http methods, C# properties also Knowledge of MVC will be plus point. AudienceThis tutorial is for beginners and professionals to learn Web API and RESTful services. ProblemsThis tutorial is available in a simple and easy language still, if there is any confusion, kindly post the doubt in the contact form.
|