Thursday, December 9, 2021

Web API Interview Questions

 

What is Web API and why we use it ?

“Web API (Application Programming Interface), as the name suggests, is an API that can be accessed over the Web using the HTTP protocol. It is basically considered the best platform for revealing or uncovering data and services to various different services. It is a tool that can be used to push data to a server and can be accessed by server code. It can be built or developed using various technologies like java, ASP.NET, etc.

Web API Uses:

It contains additional layers that simply standardize communications and provide different options on how to format input and output.
It can be used with ASP.NET MVC and different types of web applications such as ASP.NET WebForms.
If one wants to create resource-oriented services, then Web API services are considered the best.
It also helps to develop REST-ful services and SOAP-based services.”

Why is the Web API important?

“Web API is generally considered as a service that basically provides us information or data from the server. It is very important because of the following reasons:

It is used to provide an interface for websites and client applications to have access to data.
It can also be used to access data from the database and save data back to the database.
It supports different text formats such as XML, JSON, etc.
It is suitable or compatible with any type of browser and any type of device like mobile, desktop, web, etc.
It uses low bandwidth such as XML or JSON data, etc., and is therefore considered good for devices that have limited bandwidth such as smartphones, etc.
From a business point of view, web API is more applicable for UI/UX, increases interest in the company’s product and services, increases website traffic.”

What are the main return types supported in Web API?

It does not have any specific data type. It can return data of any type depending upon the business requirement. There are many HTTP methods like GET, POST, PUT, etc., which can return data in different formats depending upon the use case.

Why to choose Web API over WCF?

“Web API is considered the best choice over WCF because of the following reasons:

Web API uses all features of HTTP such as URIs, request/response headers, caching, versioning, various content formats, etc.
One does not have to define or explain any extra config setting for different devices in Web API.
Web API uses different text formats including XML because of which it is faster and more preferred for lightweight services.
Web API also supports MVC features whereas WCF does not support MVC features.
Web API provides more flexibility as compared to WCF.
Web API uses standard security like token authentication, basic authentication, etc., to provide secure service whereas WCF uses WS-I standard to provide secure service. “

What are the advantages of using Rest in Web API?

“REST is very important and beneficial in Web API because of the following reasons:

It allows less data transfer between client and server.
It is easy to use and lightweight.
It provides more flexibility.
It also handles and controls various types of calls, returning various data formats.
It is considered best for using it in mobile apps because it makes less data transfer between client and server.
It uses simple HTTP calls for inter-machine communication rather than using more complex options like CORBA, COM+, SOAP, or RPC. “

What is Web API 2.0?

“It is basically an enhanced and modified feature of Web API. This new version supports various new features as given below:

New Routing Attribute
Secure ASP.NET Web API using OAuth 2.0
Support for Cross-Origin requests using CORS
IHttpActionResult return type
Support for $expand, $select in OData Service
Because of all the new features of Web API 2.0, it is considered an optimal choice and suitable development model that makes it easier to develop RESTful services interfaces to different clients running on various platforms. It also supports configuring routes in the Web API method or controller level.”

Web API supports which protocol?

Web API generally supports only HTTP protocol. 

Which of the following Open-source libraries is used by WEB API for JSON serialization?

Json.NET library is generally used by Web API for JSON serialization. 

What is XML and JSON?

“XML (Extensible Markup Language):

It is especially designed to store and transport data.
It is similar to HTML but is more flexible than HTML because it allows users to create their own custom tags.
It is used for representing structured information such as documents, data, configuration, etc.

JSON (JavaScript Object Notation):

It is a lightweight format designed to store and transport data.
It is easier to understand and is a standard text-based format used for representing structured data based on JavaScript object syntax.
It is faster and easier to use. “

What are Web API filters?

“Filters are basically used to add extra logic at different levels of Web API framework request processing. Different types of Web API filters are available as given below:

Authentication Filter: It handles authentication and authenticates HTTP requests. It also helps to authenticate user detail. It checks the identity of the user.
Authorization Filter: It handles authorization. It runs before controller action. This filter is used to check whether or not a user is authenticated. If the user is not authenticated, then it returns an HTTP status code 401 without invoking the action.
AuthorizeAttribute is a built-in authorization filter provided by Web API.
Action Filter: It is attributing that one can apply to controller action or entire controller. It is used to add extra logic before or after controller action executes. It is simply a way to add extra functionality to Web API services.
Exception Filter: It is used to handle exceptions that are unhandled in Web API. It is used whenever controller actions throw an unhandled exception that is not HttpResponseException. It will implement an “IExceptionFilter” interface.
Override Filter: It is used to exclude specific action methods or controllers from the global filter or controller level filter. It is simply used to modify the behavior of other filters for individual action methods. “

Who can consume Web API?

A large range of clients such as browsers, mobile devices, iPhone, etc., include or consume web API. It is also good for using along native applications that require web services but not SOAP support. It can also be consumed by any client that supports HTTP verbs such as GET, DELETE, POST, PUT.

How to handle errors in Web API?

Web API generally provides greater flexibility in terms of handling errors. Exception handling is a technique that is used to handle run-time errors in application code. One can use HttpResponseException, HttpError, Exception filters, register exception filters, Exception handlers to handle errors. Exception filter can be used to identify unhandled exceptions on actions or controllers, exception handlers can be used to identify any type of unhandled exception application-wide, and HttpResponseException can be used when there is the possibility of an exception.

What is ASP.NET Web API?

“ASP stands for Active server pages. ASP.NET is an updated version of legacy ASP. It is a framework that is used for developing HTTP services to provide responses to client requests. It can be accessed in different applications on different platforms. It is provided by Microsoft open-source technology for developing and consuming HTTP-based services on top of .NET Framework. It is very easy to build HTTP services using ASP.NET Web API. These services can be used by different clients as given below:

Desktop Applications
Mobile Applications
IOTs
Browsers”

What are the advantages of using ASP.NET Web API?

“Some of the core advantages of using ASP.NET Web API are given below:

It provides the best platform for developing RESTful applications on .NET Framework.
It works the same way that HTTP works with help of HTTP verbs such as GET, POST, PUT, DELETE for all crud operations.
It provides enough flexibility in Web API creation.
It completely supports routing.
It also supports model binding, validation, Odata (Open Data Protocol) that allows creation and consumption of RESTful APIs.
It has the ability to develop custom help and test pages with help of ApiExplorer.
One can develop non-SOAP-based services such as plain XML, JSON strings, etc.
It also increases the TDD (Test Data-Driven) approach in the development of RESTful services. “

What is 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.

// GetEmployee action
public HttpResponseMessage GetEmployee(int id)
{
Employee emp = EmployeeContext.Employees.Where(e => e.Id == id).FirstOrDefault();
if (emp != null)
{
return Request.CreateResponse(HttpStatusCode.OK, emp);
} else
{
return Request.CreateErrorResponse(HttpStatusCode.NotFound, “”Employee Not Found””);
}
}”

What is the difference between ApiController and Controller?

“ApiController: It is used to return data that is arranged in series and then sent to the client.

public class TweetsController : ApiController
{
// GET: /Api/Tweets/
public List Get()
{
return Twitter.GetTweets();
}
}
Controller: It is used to provide normal views.

public class TweetsController : Controller
{
// GET: /Tweets/ [HttpGet] public ActionResult Index()
{
return Json(Twitter.GetTweets(), JsonRequestBehavior.AllowGet);
}
}”

What do you mean by Caching and What are its types?

“Caching is basically a technique or process of storing data somewhere or in the cache for future requests. The cache is a temporary storage area. Caching keeps all frequently or recently accessed files or data in the cache memory and accesses them from the cache itself rather than actual address of data or files. The cache interface simply improves the storage mechanism for request/response object pairs that are being cached.

Advantages of Caching:

It is considered the best solution to ensure that data is served where it is needed to be served that too at a high level of efficiency which is best for both client and server.
It delivers web objects faster to the end-user.
It reduces load time on the website server.
It leads to faster execution of any process.
It decreases network costs.
Types of Caching:
There are basically three types of caching as given below:

Page Caching
Data Caching
Fragment Caching”

WCF is replaced by ASP.NET Web API. True/False?

“WCF: It is a framework used for developing SOAP (Service Oriented Applications Protocols). It also supports various transport protocols as given above.
ASP.NET Web API: It is a framework used for developing non-SOAP-based services. It is limited to HTTP-based services.

No, it’s not true that ASP.NET Web API has replaced WCF. WCF was generally developed to develop SOAP-based services. ASP.NET Web API is a new way to develop non-SOAP-based services such as XML, JSON, etc. WCF is still considered a better choice if one has their service using HTTP as the transport and they want to move to some other transport like TCP, NetTCP, MSMQ, etc. WCF also allows one-way communication or duplex communication. “

What is ASP.NET Web API routing?

“Routing is the most important part of ASP.NET Web API. Routing is a way how Web API matches a URI to an action. It is basically a process that decides which action and controller should be called. The controller is basically a class that handles all HTTP requests. All public methods of controllers are basically known as action methods or just actions. Whenever a Web API framework receives any type of request, it routes that request to action.

There are basically two ways to implement routing in Web API as given below:
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. “

How to secure ASP.NET Web API?

“Web API has become key to programming web-based interactions. It can be accessed by anyone who knows the URL. Therefore, they have become targets for hackers. One needs to secure Web API by controlling Web API and by deciding who can and who cannot have access to Web API. There are basically two ways or techniques that make our Web API more secure.

Authentication: It is a process that helps to identify and check users by their credentials such as password, username, etc. To have access to the web API, firstly user credentials are needed to be passed in the request header. If user credentials are not passed into the request header, then the server returns 401 status code (unauthorized). The best authentication to be used is OAuth 2.0.

Authorization: It is a process that helps to decide whether or not a user has access to perform an action. Authorization filters are used to implement authorization.”

What are Exception filters in ASP.NET Web API?

Exception filter is generally used to handle all unhandled exceptions that are generated in web API. It implements IExceptionFilters interface. It is the easiest and most flexible to implement. This filter is executed whenever the controller method throws any unhandled exception at any stage that is not an HttpResponseExecption exception.

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.

What is HttpConfiguration in Web API?

“It is considered as the main class that includes different properties with help of which one can override the default behavior of Web API.

Some properties are given below:

DependencyResolver: It sets or gets a dependency resolver for dependency injection.
Services: It gets web API services.
ParameterBindingRules: It gets a collection of rules for how parameters should be bound.
MessageHandlers: It sets or gets message handlers.
Formatters: It sets or gets media-type formatters.”

Can we return View from ASP.NET Web API method?

No, we cannot return the view from the ASP.NET Web API method. ASP.NET web API develops HTTP services that provide raw data or information. ApiController in ASP.NET MVC application only renders data that is serialized and sent to the client. One can use a controller to provide normal views.

What is content negotiation in ASP.Net Web API?

Content negotiation is basically a process of selecting the best representation from multiple representations that are available for a given response. It simply allows one to choose rather than negotiate content that one wants to get in response. It is performed at the server-side. In simple words, it chooses the best media type for matters to return a response to an incoming request.

What parameters can be passed in the URL of API?

Context keys, documents keys, or anything that initiates API to hit the exact end-point are few parameters that one can pass in the URL to define the complete end-point.  

What is the use of DelegatingHandler?

DelegatingHandler is used to develop a custom Server-Side HTTP Message Handler in ASP.NET Web API. It is used to represent Message Handlers before routing in Web API. 

Web API uses which library for JSON serialization?

Json.NET library is used by Web API for JSON serialization. 

Explain method to handle error using HttpError in Web API?

CreateErrorResponse is an extension method that can be used in Web API controller methods to return error codes and error messages. It creates an HttpError object and then wraps it inside an HttpResponseMessage object.

How to unit test Web API?

“Using Web API tools like Fiddler, we can perform unit testing in Web API. Fiddler is basically a free debugging proxy for any browser that can be used to compose and execute various HTTP requests to Web API and check HTTP response. It is simply used for testing restful web services. It allows one to inspect and check both incoming and outgoing data to monitor and modify requests and responses before the browser receives them. Below is given some setting that is needed to be done fiddler:

Fiddler – Compose Tab -> Enter Request Headers -> Enter Request Body and then execute.”

What is Web API?

WebAPI is a framework which helps you to build/develop HTTP services.

Why is Web API required? Is it possible to use RESTful services using WCF?

“Yes, we can still develop RESTful services with WCF. However, there are two main reasons that prompt users to use Web API instead of RESTful services.

Web API increases TDD (Test Data Driven) approach in the development of RESTful services.
If we want to develop RESTful services in WCF, you surely need a lot of config settings, URI templates, contracts & endpoints for developing RESTful services using web API.”

What are the advantages of Web API?

“Advantages of Web API are:

OData
Filters
Content Negotiation
Self-Hosting
Routing
Model Bindings

Web API uses which of the following open-source library for JSON serialization?

Web API uses Json.NET library for JSON serialization.

How do you construct HtmlResponseMessage?

“Following is the way to construct to do so,

public class TestController : ApiController

{

public HttpResponseMessage Get()

{

HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, “”value””);

response.Content = new StringContent(“”Testing””, Encoding.Unicode);

response.Headers.CacheControl = new CacheControlHeaderValue()

{

MaxAge = TimeSpan.FromMinutes(20)

};

return response;

}

}”

What is Web API Routing?

“Routing is pattern matching like in MVC.

All routes are registered in Route Tables.

For example:

Routes.MapHttpRoute(

Name: “”ExampleWebAPIRoute””,

routeTemplate: “api/{controller}/{id}

defaults: new { id = RouteParameter.Optional}”

How can we use Web API with ASP.NET Web Form?

“Web API can be used with ASP.NET Web Form

It can be performed in three simple steps:

Create a Web API Controller,
Add a routing table to Application_Start method of Global.sax
Then you need to make a jQuery AJAX Call to Web API method and get data.”

How to you can limit Access to Web API to Specific HTTP Verb?

Attribute programming plays a important role. It is easy to restrict access to an ASP.NET Web API method to be called using a particular HTTP method.

Can you use Web API with ASP.NET Web Form?

Yes, It is possible to use Web API with ASP.Net web form. As it is bundled with ASP.NET MVC framework. However, it can be used with ASP.NET Web Form.

How Can assign alias name for ASP.NET Web API Action?

“We can give alias name for Web API action same as in case of ASP.NET MVC by using “”ActionName”” attribute as follows:

[HttpPost]

[ActionName(“”SaveStudentInfo””)]

public void UpdateStudent(Student aStudent)
{
StudentRepository.AddStudent(aStudent);
}”

What is the meaning of TestApi?

TestApi is a utility library of APIs. Using this library tester developer can create testing tools and automated tests for a .NET application using data-structure and algorithms.

Explain exception filters?

It will be executed when exceptions are unhandled and thrown from a controller method. The reason for the exception can be anything. Exception filters will implement “IExceptionFilter” interface.

How can we register exception filter from the action?

“We can register exception filter from action using following code:

[NotImplExceptionFilter]

public TestCustomer GetMyTestCustomer(int custid)

{

//write the code

}”

No comments:

Post a Comment

How to register multiple implementations of the same interface in Asp.Net Core?

 Problem: I have services that are derived from the same interface. public interface IService { } public class ServiceA : IService { ...