0% found this document useful (0 votes)
0 views

ASP WEB API 2

This tutorial covers the fundamentals of ASP.NET Web API, including its definition, features, and the principles of RESTful services. It explains the differences between Web API, MVC, and WCF, as well as the methods used in REST API for CRUD operations. Additionally, it provides a step-by-step guide to implementing a simple REST API application for managing student data.

Uploaded by

cybertronics2024
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

ASP WEB API 2

This tutorial covers the fundamentals of ASP.NET Web API, including its definition, features, and the principles of RESTful services. It explains the differences between Web API, MVC, and WCF, as well as the methods used in REST API for CRUD operations. Additionally, it provides a step-by-step guide to implementing a simple REST API application for managing student data.

Uploaded by

cybertronics2024
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 20

ASP.

NET Web API Tutorial

In this tutorial, we will discuss the following topics:

o What is Web API?


o Who uses API?
o ASP.NET Web API
o ASP.NET Web API features
o RESTful services
o Principles of REST API
o Methods of REST API
o Implementing REST API Simple application
o Need for Web API
o MVC vs. Web API
o Web API vs. WCF
o Web API vs. Web Services
o Web API Security
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?


o Web API is the enhanced form of the web application to provide
services on different devices like laptop, mobile, and others.
o Today, all kind of businesses use the internet as a cost-effective way to
expand their business in the international market.
o Web application helps to exchange information on the internet and
also helps to perform a secure transaction on web sites.
o 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.
o For example, Facebook (a social networking web application), Flickr (a
photo-sharing web application), and Wikipedia are majorly used
example of a web application.
o 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.

o A web application is Human-System interaction.


o 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:

o Web Browsers
o Mobile applications
o Desktop applications
o IOTs (Internet of Things)

ASP.NET Web API


API 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:

o Web Browsers
o Mobile applications
o Desktop applications
o 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 features


1) ASP.NET Web API is much similar to ASP.NET MVC.

2) It contains similar features as ASP.NET MVC like:


o Routing
o Controllers
o Action results
o Filter
o 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
o Web API is the enhanced form of a web application.
o SOAP (Simple Object Access Protocol) was an XML based protocol
for developing the connected web applications.
o Problem with the SOAP was that with each request, Metadata is
attached with data to be transferred.
o This Metadata converts small data to heavy data on the server.
o Web API may or may not be RESTful services, but they are
always HTTP based services.
o REST stands for Representational State Transfer.
o In REST API, only the state of the object is sent to the server to find
the desired result.
o 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 API
The six principles of REST API are:

1. Stateless
2. Client-Server
3. Uniform Interface
4. Cacheable
5. Layered System
6. 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:

o Resource Identification
o Resource Manipulation using representations
o Self-descriptive massages
o 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


o Working on web technologies, we work on CRUD applications.
o In these applications, CRUD is to CREATE, READ, UPDATE, and DELETE
a resource.
o Here, a resource is defined as the desired result. For example:
https://in.bookmyshow.com/noida/movies
o 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.
o 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


part of the CRUD.
It is used to create a

Method refers to the


Read GET part of the CRUD.
It is used to read a r

Method refers to the


Update PUT part of the CRUD.
It is used to update

Method refers to the


Delete DELETE part of the CRUD.
It is used to delete a

o REST API is best used for distributed systems.


o 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 application


Let's create a REST API service for students.

o Firstly open Visual Studio (here we have Visual Studio 2019).


o Now select Create a new project:
o Now select the template ASP.NET Web Application (.NET Framework)
with C# and name the project as "WebApiStudentsSample".

o In the ASP.NET Project dialog, select the Empty template and also
check Web API option. Click OK.
o A default structure generated will be as follows:

Adding Student.cs class to the Models folder

o 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.
o 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:

1. namespace WebApiStudentsSample.Models
2. {
3. public class Students
4. {
5. public int StudentId
6. {
7. get;
8. set;
9. }
10. public string StudentName
11. {
12. get;
13. set;
14. }
15. public string Address
16. {
17. get;
18. set;
19. }
20. public string Course
21. {
22. get;
23. set;
24. }
25.
26. }
27. }
Adding StudentControllers.cs class to Controllers folder

o Controller class handles HTTP request from the client, which may be a
desktop application, mobile device, and browser.
o Right-click on Controllers, Select Add option, and then select
'Controller..'.

Add Scaffold window will open then Select Web API2 Controller ?
Empty template.
o 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.
o 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:

1. using System;
2. using System.Collections.Generic;
3. using System.Linq;
4. using System.Net;
5. using System.Net.Http;
6. using System.Web.Http;
7. using WebApiStudentsSample.Models;
8.
9. namespace WebApiStudentsSample.Controllers
10. {
11. public class StudentController : ApiController
12. {
13. IList<Students> Students = new List<Students>()
14. {
15. new Students()
16. {
17. StudentId = 1, StudentName = "Mukesh Kumar", Ad
dress = "New Delhi", Course = "IT"
18. },
19. new Students()
20. {
21. StudentId = 2, StudentName = "Banky Chamber", A
ddress = "London", Course = "HR"
22. },
23. new Students()
24. {
25. StudentId = 3, StudentName = "Rahul Rathor", Addr
ess = "Laxmi Nagar", Course = "IT"
26. },
27. new Students()
28. {
29. StudentId = 4, StudentName = "YaduVeer Singh", A
ddress = "Goa", Course = "Sales"
30. },
31. new Students()
32. {
33. StudentId = 5, StudentName = "Manish Sharma", Ad
dress = "New Delhi", Course = "HR"
34. },
35. };
36. public IList<Students> GetAllStudents()
37. {
38. //Return list of all employees
39. return Students;
40. }
41. public Students GetStudentDetails(int id)
42. {
43. //Return a single employee detail
44. var Student = Students.FirstOrDefault(e => e.StudentId
== id);
45. if (Student == null)
46. {
47. throw new HttpResponseException(Request.CreateRe
sponse(HttpStatusCode.NotFound));
48. }
49. return Student;
50. }
51. }
52. }
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 Identifie

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


o A Web API helps to access service data from different internet devices
like browsers, mobile apps, and other devices.
o Helps to work on RESTful web services.
o Helps to develop light weighted and maintainable Web Services.
o Used to create both types of services RESTful and non-RESTful
services.
o Also supports JSON, XML, and other data formats.
o Helps to develop services supporting all features of HTTP services such
as like caching, request/response headers, versioning, etc.

MVC vs. Web API


Differences between ASP.NET API and ASP.NET MVC are as follows:

MVC Web API

Helps to develop HTTP services (REST


Helps to develop web applications that process
RESTful services) that process the re
the request and sends both views and data.
returns data only, not a view.

Represents resultant data in JSON format using Return data in particular format like J
JsonResult. any other format

A request is mapped to actions name. A request is mapped to HTTP verbs in

Same features are available in Web A


Model binding, routing, and other features are
these features are defined in System
defined in System.Web.Mvc.
assembly.

Supports feature of content-negotiati


MVC usually interact with the views to provide
deciding the best format for response
final output
compatible with the client machine.

Web API vs. WCF


Differences between ASP.NET WCF and ASP.NET Web API are as follows:
Feature Web API WCF

Web API supports any media WCF supports SOAP


Content format
format like XML, JSON, etc. services and XML fo

WCF supports works


Web API supports IIS hosting,
Hosting services and also IIS
Self-hosting
Self-hosting.

ASP.NET Web API supports Like MVC, WCF does


features like controllers, any features like co
MVC features
routing, action, etc. same as routing, filter, auctio
MVC. etc.

UDP, HTTP, and cus


Web API supports HTTP
Protocol transport protocol a
protocol.
supported.

ServiceContract a
defines a Service Co
contains operations
OperationContrac
Uses HTTP verbs as methods defines the operatio
Use of model
called as CRUD operations be used.
DataContract attri
the properties or typ
be transferred betw
parties.

Web API vs. Web Services


Differences between Web API and Web services are as follows:

Features Web API Web services

Hosting Hosting is done within an Hosting is done on I


application or IIS.

Web API is open-source, and it Web service is not o


Open Source can be used by any client that but can be used by
supports JSON or XML. that supports XML.

Web API is light-weighted It requires a SOAP p


architecture and good for receive and send da
Architecture
devices which have limited network, so it is not
bandwidth, like mobile devices. architecture.

It supports the HTTP protocol:


URL, Request/Response It supports the HTTP
Protocol
Headers, versioning, caching, only.
content formats.

Web API Security


ASP.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.

o 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.
o 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).

Prerequisite
Before learning Web API, the user must have basic knowledge of Http methods,
C# properties also Knowledge of MVC will be plus point.

Audience
This tutorial is for beginners and professionals to learn Web API and RESTful
services.

Problems
This tutorial is available in a simple and easy language still, if there is any
confusion, kindly post the doubt in the contact form.

https://www.javatpoint.com/web-api

You might also like