Wednesday, February 16, 2022

Web API Interview Questions

 

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

2. Rest API principals?

REST (Representational State Transfer) is a software architectural style used for creating web services. The principles of REST API are as follows:

  1. Client-Server Architecture: The client and server are separated from each other, allowing them to evolve independently without affecting the other.
  2. Stateless: Each request to the server must contain all the necessary information for the server to fulfill the request. The server should not maintain any client state between requests.
  3. Uniform Interface: The interface between the client and the server should be standardized, and resources should be identified by a URI (Uniform Resource Identifier).
  4. Cacheable: Responses from the server should be cacheable to improve performance and reduce the number of requests to the server.
  5. Layered System: The architecture should be composed of layers, where each layer only interacts with the layer directly below or above it. This allows for scalability and flexibility.
  6. Code on Demand (Optional): The server can send executable code to the client, which can then be executed within the client's environment.

These principles are designed to create web services that are scalable, flexible, and easy to maintain. By adhering to these principles, RESTful APIs can be created that are interoperable and can be used by a wide range of clients, including browsers, mobile devices, and other web services.

3. What is the difference between Web API and WCF?

Web API and WCF (Windows Communication Foundation) are both technologies used for creating web services in .NET, but there are some differences between them:

  1. Purpose: Web API is primarily designed for creating RESTful services that use HTTP as the communication protocol, while WCF can be used for creating both RESTful and SOAP-based services.
  2. Programming Model: Web API uses a simple programming model based on MVC (Model-View-Controller) principles, which makes it easy to develop and maintain web services. WCF, on the other hand, has a more complex programming model that offers a wide range of features and flexibility.
  3. Hosting: Web API can be hosted in IIS or in any other hosting environment that supports HTTP. WCF, on the other hand, can be hosted in IIS, Windows Services, or any other hosting environment.
  4. Data Format: Web API primarily uses JSON (JavaScript Object Notation) and XML (Extensible Markup Language) as the data format, while WCF supports a wider range of data formats, including JSON, XML, and binary formats.
  5. Protocol Support: Web API supports only HTTP as the communication protocol, while WCF supports a wide range of protocols, including HTTP, TCP, and named pipes.
  6. Platform Support: Web API is a part of the ASP.NET framework and can be used with any .NET language. WCF, on the other hand, is a separate framework that can be used with any .NET language and can also be used with non-.NET languages such as Java and PHP.

In summary, Web API is a simpler and more lightweight framework primarily designed for creating RESTful services using HTTP, while WCF is a more complex framework that offers a wide range of features and flexibility for creating both RESTful and SOAP-based services using a variety of communication protocols.

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

5. 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. 
  • It works the same way that HTTP works with help of HTTP verbs such as GET, POST, PUT, DELETE for all crud operations.
  • It completely supports routing.
  • It also supports model binding, validation, Odata (Open Data Protocol) that allows creation and consumption of RESTful APIs.
  • One can develop non-SOAP-based services such as plain XML, JSON strings, etc.

6. What is SOAP? What is different between them?

SOAP (Simple Object Access Protocol) API is a messaging protocol used for communication between web services. It is a protocol for exchanging structured data between applications over the internet. SOAP API uses XML (Extensible Markup Language) as its message format and relies on HTTP (Hypertext Transfer Protocol), Simple Mail Transfer Protocol (SMTP) and Transmission Control Protocol or other communication protocols for transmitting messages between web services.
The SOAP message consists of a header and a body. The header contains information about the message, such as the type of message, any security credentials required, and routing information. The body contains the actual data being transmitted, which can be in any format supported by XML, such as text, numbers, or complex data types.
SOAP API is often used for enterprise-level applications that require a high degree of reliability and security. It includes built-in error handling and fault tolerance mechanisms, making it highly reliable. It also includes built-in security features such as encryption and digital signatures, making it highly secure.
SOAP API has several advantages over other web service protocols, including its reliability, security, interoperability, and standardization. However, it also has some disadvantages, including its complexity and overhead, which can result in slower performance compared to other web service protocols.
Overall, SOAP API is a powerful and reliable protocol for web services, but it may not be the best choice for every application due to its complexity and overhead.

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

8. Explain media type formatters.

Media type formatters are a type of component in web API frameworks that are responsible for serializing and deserializing data in various formats.

Media Type
Formatter Class
MIME TypeDescription
JsonMediaType
Formatter
application/json, text/jsonHandles JSON format
XmlMediaType
Formatter
application/xml, text/jsonHandles XML format
FormUrlEncoded MediaTypeFormatterapplication/x-www-form-urlencodedHandles HTM form URL-encoded data
JQueryMvcFormUrl EncodedFormatterapplication/x-www-form-urlencodedHandles model-bound HTML form URL-encoded data

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

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

11. Who can consume Web API?

A large range of clients such as browsers, mobile devices, iPhone, etc., include or consume web API. 

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

13. What is MVC? Write difference between MVC and Web API?

MVC (Model, View, and Controller) is basically an application design model that comprises three interconnect parts I.e., model, view, and controller. It allows coders to factor out different components of the application and update them more easily. It is mostly used for developing model user interfaces. Its main purpose is to display patterns in structure for keeping display and data separate to enable both of them to change without affecting others. 

MVCWeb API
It can be used to build Web applications that reply as both data and views.It is used to build HTTP services that reply only as data.
It returns data in JSON format by using JSONResult.It returns data in different formats such as JSON, XML, etc.
It supports content negotiation, self-hosting.It does not support content negotiation, self-hosting.
It is not able to build REST-full services.It is very helpful in creating REST-full services.
It returns a view (HTML).It returns REST responses.

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

True and False, it depends on the context and specific requirements of the project.

WCF (Windows Communication Foundation) and ASP.NET Web API are both technologies for building web services in the .NET framework. However, they have different focuses and use cases.

WCF provides a unified platform for building distributed applications, supporting multiple transport protocols and message patterns, and allows the creation of services that can communicate with each other across different platforms and technologies. It is a mature technology that has been used in a wide range of scenarios, including enterprise-level systems, and provides features like message-level security, transactions, and reliability.

On the other hand, ASP.NET Web API is a lightweight framework for building RESTful services that can be consumed by a wide range of clients, including web browsers, mobile devices, and desktop applications. It is optimized for HTTP-based services and supports features like content negotiation, caching, and authentication.

Therefore, while ASP.NET Web API can be used to build web services that provide similar functionality to WCF, it may not be the best choice for all scenarios. It depends on the specific requirements and constraints of the project, and the developer's expertise and familiarity with the technology.

15. What are the main return types supported in ASP. Net Web API?

It supports the following return types:

  • HttpResponseMessage
  • IHttpActionResult
  • Void
  • Other types such as string, int, etc. 

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

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

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

19. What is CORS in Web API?

CORS (Cross-Origin Resource Sharing) is basically a mechanism that allows one to make requests from one website to another website in a browser that is normally not allowed by another policy called SOP (Same Origin Policy). It supports secure cross-origin requests and data transfers among clients or browsers and servers. Here, cross-origin request means requests coming from different origins. CORS simply resolves the same-origin restriction for JavaScript. One can enable CORS for web API using the respective web API package or OWIN middleware. 

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

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

22.What are the different HTTP methods used in Web API?

Though there are a variety of HTTP verbs or methods, the most important and frequently used ones are GET, PUT, POST and DELETE.  

GET – It is used to retrieve information of the resource at a specified URI.

PUT – The PUT method is used to update the values of a resource at a specified URI.

POST –POST method is used to create a new request and send data to the respective server. 

DELETE –This method is used to remove the current resource at a specified URI.

TRACE- This method performs a message loop-back test along the path to the target resource, providing a useful debugging mechanism.

CONNECT - This method starts two-way communications with the requested resource. It can be used to open a tunnel.

OPTIONS - This method requests permitted communication options for a given URL or server. A client can specify a URL with this method, or an asterisk (*) to refer to the entire server.

HEAD - This method identical to GET except that the server MUST NOT return a message-body in the response. The metainformation contained in the HTTP headers in response to a HEAD request SHOULD be identical to the information sent in response to a GET request.

23. What is PREFLIGHT request?

The browser asks for permissions by using what is called a preflight request. A preflight request is a small request that is sent by the browser before the actual request. It contains information like which HTTP method is used, as well as if any custom HTTP headers are present. The preflight gives the server a chance to examine what the actual request will look like before it’s made. The server can then indicate whether the browser should send the actual request, or return an error to the client without sending the request.

a preflight request asks for the server’s permission to send the request. The preflight isn’t the request itself. Instead, it contains metadata about it, such as which HTTP method is used and if the client added additional request headers. The server inspects this metadata to decide whether the browser is allowed to send the request.

24. What is the commonly observed HTTP response status code?

HTTP status codes are three-digit integers issued by the server in response to the request made by the client, where each number specifies a meaning. 

All HTTP status codes are categorized into five classes. These include –

  • 1xx (Informational) – It indicates that the server has received a certain request and the process is continuing. 
  • 2xx (Successful)–It indicates that the request was successful and accepted. 
  • 3xx (Redirection)–It indicates that the request has been redirected and its completion will require further action or steps. 
  • 4xx (Client Error)–It indicates that the request for the web page cannot be reached as either it is unavailable or has bad syntax. 
  • 5xx (Server Error)–It indicates that the server was unable to complete a certain request even though the request seems valid. 

Here are the most commonly seen HTTP status codes at a glance –

  • Status code 200 – request is ok.
  • Status code 201 – Created 
  • Status code 202 – Accepted 
  • Status code 204 – No content 
  • Status code 301 – Moved permanently 
  • Status code 400 – Bad request 
  • Status code 401 – Unauthorized 
  • Status code 403 – Forbidden 
  • Status code 404 – Not found 
  • Status code 500 – Internal server error 
  • Status code 502 – Bad gateway 
  • Status code 503 – Service Unavailable 

1xx: Information

MessageDescription
100 ContinueOnly a part of the request has been received by the server, but as long as it has not been rejected, the client should continue with the request.
101 Switching ProtocolsThe server switches protocol.

2xx: Successful

MessageDescription
200 OKThe request is OK.
201 CreatedThe request is complete, and a new resource is created .
202 AcceptedThe request is accepted for processing, but the processing is not complete.
203 Non-authoritative InformationThe information in the entity header is from a local or third-party copy, not from the original server.
204 No ContentA status code and a header are given in the response, but there is no entity-body in the reply.
205 Reset ContentThe browser should clear the form used for this transaction for additional input.
206 Partial ContentThe server is returning partial data of the size requested. Used in response to a request specifying a Range header. The server must specify the range included in the response with the Content-Range header.

3xx: Redirection

MessageDescription
300 Multiple ChoicesA link list. The user can select a link and go to that location. Maximum five addresses  .
301 Moved PermanentlyThe requested page has moved to a new url .
302 FoundThe requested page has moved temporarily to a new url .
303 See OtherThe requested page can be found under a different url .
304 Not ModifiedThis is the response code to an If-Modified-Since or If-None-Match header, where the URL has not been modified since the specified date.
305 Use ProxyThe requested URL must be accessed through the proxy mentioned in the Location header.
306 UnusedThis code was used in a previous version. It is no longer used, but the code is reserved.
307 Temporary RedirectThe requested page has moved temporarily to a new url.

4xx: Client Error

MessageDescription
400 Bad RequestThe server did not understand the request.
401 UnauthorizedThe requested page needs a username and a password.
402 Payment RequiredYou can not use this code yet.
403 ForbiddenAccess is forbidden to the requested page.
404 Not FoundThe server can not find the requested page.
405 Method Not AllowedThe method specified in the request is not allowed.
406 Not AcceptableThe server can only generate a response that is not accepted by the client.
407 Proxy Authentication RequiredYou must authenticate with a proxy server before this request can be served.
408 Request TimeoutThe request took longer than the server was prepared to wait.
409 ConflictThe request could not be completed because of a conflict.
410 GoneThe requested page is no longer available .
411 Length RequiredThe "Content-Length" is not defined. The server will not accept the request without it .
412 Precondition FailedThe pre condition given in the request evaluated to false by the server.
413 Request Entity Too LargeThe server will not accept the request, because the request entity is too large.
414 Request-url Too LongThe server will not accept the request, because the url is too long. Occurs when you convert a "post" request to a "get" request with a long query information .
415 Unsupported Media TypeThe server will not accept the request, because the mediatype is not supported .
416 Requested Range Not SatisfiableThe requested byte range is not available and is out of bounds.
417 Expectation FailedThe expectation given in an Expect request-header field could not be met by this server.

5xx: Server Error

MessageDescription
500 Internal Server ErrorThe request was not completed. The server met an unexpected condition.
501 Not ImplementedThe request was not completed. The server did not support the functionality required.
502 Bad GatewayThe request was not completed. The server received an invalid response from the upstream server.
503 Service UnavailableThe request was not completed. The server is temporarily overloading or down.
504 Gateway TimeoutThe gateway has timed out.
505 HTTP Version Not SupportedThe server does not support the "http protocol" version.

No comments:

Post a Comment