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

API Is An Abbreviation For Application Programming Interface1

Uploaded by

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

API Is An Abbreviation For Application Programming Interface1

Uploaded by

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

API is an abbreviation for Application Programming Interface.

ASP.NET Web API ;


A Web API is a Web application programming interface.

ASP.NET Web API is a framework for building HTTP services that


can be accessed from any client including in different applications
on different platforms such as web, windows, browsers and mobile
devices.
It is an ideal platform for building RESTful applications on the
.NET Framework.
A Browser API can be used to enhance a web browser's functionality. A
Server API can be used to enhance a web server's functionality.
.

ASP.NET Web API Characteristics


• 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.
Q1. What is the difference between ASP.NET and
API?
ASP.NET MVC Controllers are used for building web applications with dynamic
user interfaces, while Web API Controllers are used for exposing data and
services over HTTP for various clients

Q2. What is .NET Framework API?


A software development framework for building and running applications on
Windows.

Q3. What is ASP.NET Web API 2 vs 1?


WebAPI-2 supports configuring routes at the controller level or the webAPI
method level. While in WebAPI-1 you could only configure routes in the global.
asax.

Why is Web API required?


A web API is a service that retrieves information or data from a server. It
is critical for business growth. Here are some of the reasons why Web API
is so important:
• Provides a data access interface for both web pages and client
applications.
• Supports a variety of text formats, including XML and JSON.
• Works nicely on low-bandwidth devices.
• Commonly used in the creation of UI/UX, resulting in increased
visitors to the website.
• Compatibility with any browser and device.

Why select Web API?


• It is used to develop simple HTTP Services that are not SOAP-
based.
• It is also a simple way to create with Web API. REST Services with
WCF
• It is HTTP-based and simple to define, expose, and consume
RESTful.
• It is a lightweight architecture that is excellent for devices with limited
bandwidth, such as smartphones.
The advantages of Web API ;
Web API can automatically convert request and response data
into various formats, including JSON, XML, BSON, and url-encoded
data.
This makes it easy to work with data in the format that is most
convenient for you.
On the other hand, the REST API only supports the JSON data
format and is, therefore, less flexible.

When to choose ASP.NET Web API?


• Choose Web API if you are using .NET framework 4.0 or above.
• Choose Web API if you want to build a service that supports only
HTTP protocol.
• Choose Web API to build RESTful HTTP based services.
• Choose Web API if you are familiar with ASP.NET MVC.

Create Web API project


Here, you will learn how to create a new ASP.NET Web API project
using Visual Studio.

You can create a Web API project in two ways.

1. Web API with MVC Project


2. Stand-alone Web API Project

Stand-alone Web API Project


Here, we will create a new stand-alone Web API project without MVC
project.

For this, open Visual Studio 2013 for Web -> go to File menu and
select New Project.. This will open New Project popup as below.
TestApi?
TestApi is an API utility library. Using this library, tester developers can
design testing tools and automated tests for .NET applications that use
data structures and algorithms.

Test Web API


Test Web API locally to check request & response during
development.

We can use the following third party tools for testing Web API.

• Fiddler
• Postman

Web API Controllers ;


In ASP.NET Web API, a controller is a class that handles HTTP
requests.
All the public methods of the controller are called action methods.

Web API Controller Characteristics


1. It must be derived from System.Web.Http.ApiController class.
2. It can be created under any folder in the project's root folder.
However, it is recommended to create controller classes in
the Controllers folder as per the convention.
3. Action method name can be the same as HTTP verb name or it
can start with HTTP verb with any suffix (case in-sensitive) or
you can apply Http verb attributes to method.
4. Return type of an action method can be any primitive or
complex type.

The difference between ApiController and Controller?

ApiController: It is used to return data that is arranged in series and


then sent to the client.
Controller: It is used to provide normal views.

Action Method Naming Conventions


• Name of the action methods in the Web API controller
plays an important role. Action method name can be the
same as HTTP verbs like Get, Post, Put, Patch or Delete as
shown in the Web API Controller example above.
• However, you can append any suffix with HTTP verbs for
more readability.
For example, Get method can be GetAllNames(),
GetStudents() or any other name which starts with Get.

Configure Web API ;


Web API supports code based configuration. It cannot be
configured in web. config file.

We can configure Web API to customize the behaviour of Web


API hosting infrastructure and components such as routes,
formatters, filters, DependencyResolver, MessageHandlers,
ParamterBindingRules, properties, services etc.

Web API Routing ;


• Routing is how Web API matches a URI to an action. Web
API 2 supports a new type of routing, called attribute
routing.
• As the name implies, attribute routing uses attributes to
define routes. Attribute routing gives you more control over
the URIs in your web API.

• Note:
• Web API also supports routing same as ASP.NET MVC by including
action method name in the URL.
Routing can be implemented in two ways:
• Convention-based routing:

Web API supports convention-based routing.


In this type of routing, Web API uses route templates to select
which controller and action method to execute.

Attribute-based routing:

Web API 2 generally supports a new type of routing


known as attribute routing. As the name suggests, it uses attributes to
define routes.
It is the ability to add routes to the route table via
attributes. It makes use of characteristics to define and add routes to route
tables.

Parameter Binding in ASP.NET Web API ;


Parameter binding is the process of converting request data into
strongly typed parameters that are expressed by route handlers.
Binding sources can be explicit or inferred based on HTTP method
and parameter type. Supported binding sources: Route values.
HTTP Method Query String Request Body
GET Primitive Type, NA
Complex Type
HTTP Method Query String Request Body
POST Primitive Type Complex Type
PUT Primitive Type Complex Type
PATCH Primitive Type Complex Type
DELETE Primitive Type, NA
Complex Type
Note:
Query string parameter name and action method parameter name must be
the same (case-insensitive). If names do not match, then the values of the
parameters will not be set. The order of the parameters can be different.

Note:
Post action method cannot include multiple complex type parameters
because, at most, one parameter is allowed to be read from the request
body.

Note:
The [FromBody] attribute can be applied on only one primitive parameter of
an action method. It cannot be applied to multiple primitive parameters of
the same action method.

[FromUri] and [FromBody]Use [FromUri] attribute to force Web API


to get the value of complex type from the query string and
[FromBody] attribute to get the value of primitive type from the
request body, opposite to the default rules.

Action Method Return Type


Web API action method can contain any entity type as return type.
As mentioned in the first example of What is Web API Action Results,
we can use any entity type as the return type. But the problem here
is that we get 200 (OK) status code every time on a successful
response.The Web API action method can have following return
types.

1. Void
2. Primitive type or Complex type
3. HttpResponseMessage
4. IHttpActionResult
Void ;
void. If the return type is void , Web API simply returns an
empty HTTP response with status code 204 (No Content).
Type Primitive type or Complex type ;
The simplest action returns a primitive or complex data
type (for example, string or a custom object type).
Consider the following action, which returns a collection of custom Product
objects: C# Copy. [HttpGet] public List<Product> Get() => _repository. GetProducts()
HttpResponseMessage ;
A HttpResponseMessage allows us to work with the HTTP protocol
(for example, with the headers property) and unifies our return type.
In simple words an HttpResponseMessage is a way of returning a
message/data from your action.
the use of HttpResponseMessage?

It is used to set response values such as header and status control. It


simply allows us to work with HTTP protocol. It represents HTTP
response messages that encapsulate data and status code.

IHttpActionResult ;
In Web API, IHttpActionResult's ExecuteAsync method is
automatically invoked when a client calls an action method,
allowing custom logic to generate a HttpResponseMessage
asynchronously.

Web API Request/Response Data Formats ;


• Web API converts request data into CLR object and also
serialize CLR object into response data based on Accept and
Content-Type headers.
• Web API includes built-in support for JSON, XML, BSON, and
form-urlencoded data. It means it automatically converts
request/response data into these formats OOB (out-of the
box).
• Web API handles different formats of request and response
data.

Media-Type Formatters :
By using Media-Type formatters. Media type formatters
are classes responsible for serializing request/response data so
that Web API can understand the request data format and send
data in the format which client expects.

Web API Filters ;


• Web API includes filters to add extra logic before or after
action method executes.
• Filters can be used to provide cross-cutting features such as
logging, exception handling, performance measurement,
authentication and authorization.
• Filters are actually attributes that can be applied on the Web
API controller or one or more action methods. Every filter
attribute class must implement IFilter interface included in
System.Web.Http.Filters namespace..

CRUD operation ;
CRUD stands for "Create, Read, Update, and Delete," which
are the four basic database operations. Many HTTP services
also model CRUD operations through REST or REST-like
APIs.

Web API for CRUD operation ;


CRUD stands for Create, Read, Update and Delete. It works on
HTTP verbs like HttpPost to Create, HttpGet to Read, HttpPut to
Update, and HttpDelete to Delete. Many of these resources allow
create, read, update and delete operations. The REST API maps
CRUD operations to HTTP methods.
Many of these resources allow create, read, update and delete
operations.

Implement Get Method ;


Retrieving Data from APIs
Parameters for GET requests are usually passed in the URL, and
they can be appended to the end of the URL in the form of a query
string. For example, you can use a GET request to obtain
information about a specific user:
https://api.example.com/users?id=123..

Implement Post Method ;


The Post Method in the Web API application allows us to create a
new item.
A POST request sends data to an API, either creating or updating an existing resource…

The HTTP POST request is used to create a new record in the data
source in the RESTful architecture.
The action method that will handle HTTP POST request must start
with a word Post. [HTTP POST]

Implement Put Method ;


The PUT method in Web API allows us to update an item.
The action method that will handle HTTP PUT request must start
with a word Put.

Implement Delete Method ;


The HTTP DELETE request is used to delete an existing record in
the data source in the RESTful architecture.
The action method that will handle HTTP DELETE request must
start with the word "Delete".

Consume Web API ;


ASP.NET Web API is a framework for building HTTP services that can
be consumed by a broad range of clients including browsers, mobiles,
iphone and tablets.
Consuming Web API

In this article, we have used the localhost for Web API and called the GET
request.

• Create ASP.NET MVC Project


• Add MemberViewModel
• Add Microsoft.AspNet.webApi.Client from the NuGet library
• Code for consuming the Web API
• Run the project and call action method on URL

Who can consume WebAPI?


WebAPI can be used by any client that supports HTTP verbs like GET, PUT,
DELETE, and POST.

Consume Web API in ASP.NET MVC ;


HttpClient sends a request to the Web API and receives a
response.

Web API can be accessed in the server side code in .NET and also
on client side using JavaScript frameworks such as jQuery,
AnguarJS, KnockoutJS etc.

Here, we will consume our Web API (created in the previous section)
in the following environments:

1. Consume Web API in ASP.NET MVC


2. Consume Web API in AngularJS

Consume Web API in ASP.NET MVC ;


We created Web API and implemented various Get methods to
handle different HTTP GET requests in the Implement Get Method
section.
To consume Web API in ASP.NET MVC server side we can
use HttpClient in the MVC controller. HttpClient sends a request to
the Web API and receives a response. We then need to convert
response data that came from Web API to a model and then
render it into a view.

1. Define the API endpoint: Know the URL of the Web API endpoint you want
to consume.

2. Add HttpClient: In your ASP.NET MVC application, create an instance of


HttpClient to make HTTP requests to the Web API.

3. Make HTTP GET request: Use the HttpClient instance to make a GET request
to the Web API endpoint.

4. Process the response: Handle the response returned by the Web API, which
could be JSON, XML, or other formats.

Consume Web API in .NET using HttpClient ;


First, we have created an object of HttpClient and assigned
the base address of our Web API. The GetAsync() method sends
an http GET request to the specified url. The GetAsync() method is
asynchronous and returns a Task.
we will use HttpClient class in console application to send data to
and receive data from Web API which is hosted on local IIS web
server. You may use HttpClient in other .NET applications also
such as MVC Web Application, windows form application, windows
service application etc.

Configure Dependency Injection with Web API ;


In ASP.NET Web API, configure dependency injection by
registering dependencies with the chosen DI container and
injecting them into controllers via constructor injection.

Web API Hosting ;

Web API hosting involves deploying the API to a server or


cloud platform where it can be accessed by clients over the
internet.
You can host a Web API as separate process than ASP.NET. It
means you can host a Web API in console application or windows
service or OWIN or any other process that is managed by . NET
framework.

IIS Hosting ;
Web API can be hosted under IIS, in the same way as a web
application. You have learned to create a Web API in the previous
section. As you have seen there, a Web API is created with
ASP.NET MVC project by default.

Self Hosting.
You can host a Web API as separate process than ASP.NET. It
means you can host a Web API in console application or windows
service or OWIN or any other process that is managed by . NET
framework.

You need to do following steps in order to self-host a web API.

1. Use HttpConfiguration to configure a Web API


2. Create HttpServer and start listening to incoming http requests

-----------------*-------------------------
State differences between MVC and WebAPI
The MVC framework is used to create applications with user interfaces. Views
can be utilized to provide a user interface for this purpose.
WebAPI is used to create HTTP services. Other programs can also use the
WebAPI methods to retrieve the data.

the difference between Web API and WCF?

WCF is used for SOAP-based service development, whereas Web


API is utilized for both SOAP-based and RESTful service
development. WCF does not provide support for MVC
functionalities, although Web API does. WCF supports HTTP, UDP,
and custom transport protocols, whereas Web API only supports
HTTP.

what is REST and RESTFUL.


• REST stands for REpresentational State Transfer, and it is a
completely new way of developing a web program.
• RESTful services are those that are created using REST
architectural concepts. It focuses on system resources and how the
state of those resources should be transmitted via HTTP.

different between REST API and RESTful API?

REST API uses web services and is based on request and


response, whereas RESTful API works completely based on REST
application and infrastructure. REST apps have strong protocols
and pre-configured architecture layers as security measures,
whereas RESTful apps have multi-layered transport protocols.

Beetween SOAP and REST?


SOAP and REST are two different approaches to API design. The SOAP
approach is highly structured and uses XML data format. REST is more
flexible and allows applications to exchange data in multiple formats.

Web API supports which protocol?


The HTTP protocol is the primary protocol supported by Web API. This means
that it makes use of the well-established and widely recognized HTTP standards
for communication between clients and servers.

Web API supports which protocol?


Web API generally communicates over the Hypertext Transfer Protocol (HTTP).
This implies it employs HTTP methods to specify operations (GET, POST, PUT,
DELETE, etc.), and HTTP status codes to indicate response outcomes, and
often transfers data in formats like JSON or XML over HTTP.

Web API uses which library for JSON serialization?


Web API uses the Json.NET package for JSON serialization.

Which .NET framework supports ASP.NET Web API?

.NET Framework 4.0 generally supports the first version of


ASP.NET Web API. After that, .NET Framework 4.5 supports the
latest version of web API i.e., ASP.NET Web API 2

How to handle errors in Web API?


Error handling classes are accessible in Web API. HttpError,
HttpResponseException, Exception Filters, and Registering Exception Filters
are among them.
Explain the method to handle errors using HttpError
in Web API.
HttpError was used in WEB API to throw error information in the response body.
Along with this, you can use the "CreateErrorResponse" method, which is
defined in the "HttpRequestMessageExtension."

Which .NET framework supports Web API?


The following .NET frameworks enable Web API:
• .NET Framework 4.0 and later: Web API was first introduced in .NET
Framework 4.0, and it is now supported in all future versions, including
4.5, 4.6, and 4.8.
• Versions of .NET Core 1.0 and later: .NET Core, a cross-platform and
open-source version of .NET, has supported Web API since its initial
release and will continue to do so in future editions.
• .NET 5 and later: Web API is naturally supported by.NET 5 and later
versions, which unite the.NET Framework and.NET Core.

What is the biggest disadvantage of “Other Return


Types” in Web API?
The inability to directly return non-200 status codes is the most significant
downside of using "Other Return Types" in Web API.

What is SOAP?
SOAP is an XML messaging format that is commonly used in online service
interactions. It supports sending messages via HTTP or JMS, but additional
transport protocols are also supported. It is also an XML-based messaging
system used to exchange data between computers.

What is the benefit of using REST in Web API?


REST is essential and advantageous in Web API for the following reasons:
• It enables minimal data transfer between the client and the server.

• It is simple to use and light.


• It gives you additional options.
• It also manages and regulates numerous types of calls and returns data
in a variety of forms.
• It is preferred for use in mobile apps since it requires minimal data
transmission between client and server.
• It communicates between machines using basic HTTP calls rather than
more complicated choices such as CORBA, COM+, SOAP, or RPC.

error handling in Web API.


Web API provides several error-handling classes:
• HttpResponseException: Returns the HTTP status code specified in
the Constructor of the exception.
• HttpError: Uses the HttpResponseMessage to return the meaningful
error code to the client.
• Exception filters: These are useful when the controller action method
throws an unhandled exception or error

How can you restrict access methods to specific


HTTP verbs in Web API?
With the help of Attributes (like HTTP verbs), It is possible to implement access
restrictions in Web API. It is possible to define HTTP verbs as an attribute to
restrict access.

Example:
HttpPost]public void Method1(Class obj){//logic
Web service testing tools for REST APIs include:
• Jersey API
• CFX
• Axis
• Restlet

Explain the different HTTP methods.


There are 8 HTTP methods:
• GET: Uses a specific URI to retrieve data from the server.
• HEAD: Like GET, but just sends the status line and header section.
• PUT: Replace all existing resources with the uploaded content and
update them.
• POST: Send data to the appropriate server.
• DELETE: Deletes all current resources specified by a URI.
• OPTIONS: Specifies the target resource's communication options.
• CONNECT: Constructs a tunnel to the server based on a URI.
• TRACE: Runs a message loop-back test along the path to the destination
resource.
Can a Web API return an HTML View?
Web API cannot return an HTML view. If you want to return views, it is best to
use MVC.

54. What is the status code for “Empty return type”


in Web API?
The status code 204 will return empty content in the response payload body.

You might also like