Thursday, December 9, 2021

Web API Interview Questions Part 3

 

What do you understand by the RESTful Services?

“The full form of REST stands for the Representational State Transfer. Roy Fielding coined this term in 2000. RESTful is an architectural style for creating loosely coupled applications over HTTP. To make API to be RESTful, we have to follow the six constraints given below:

Client and Server Separation: Clients and Servers are isolated in the RESTful services.
Stateless: REST architecture is based on the HTTP Protocol, and the clients can cache the server response, but no client context would be stored on the server.
Uniform Interface: It is used to allow a limited set of operations defined using the HTTP Verbs. For example, GET, PUT, POST, Delete, etc.
Cacheable: RESTful architecture allows the response to be cached or not. Caching improves performance and scalability.
Code-On-Demand
Layered System

How can we restrict or limit access to Web API to Specific HTTP Verb?

A.We can easily restrict or limit access to an ASP.NET Web API method called using a particular HTTP method. In this process, attribute programming plays a crucial role.

How to use the Web API with ASP.NET Web Form?

“We can use the Web API with ASP.NET Web Form by performing the following three simple steps:

First, create a Web API Controller.
Now, add a routing table to the Application_Start method of Global. sax
Now, we can make a jQuery AJAX Call to Web API method and get the data.”

What is Not Rest?

“It is not a protocol
It is not a standard
It is not a replacement for SOAP”

What is BSON in Web API?

A.BSON stands for Binary Javascript Object Notation. BSON has the objects in the key-value pair that is faster for encoding and decoding. It is light-weighted like JSON, but it is much faster than JSON. Moreover, BSON is not in a readable format.

What are the media types of HTTP Requests and Response?

“Media types are used to specify the formats of the requests, responses, images, and texts.

Media types include:

Image/Png or Image/Jpg or Image/Jpeg
Text/HTML
Application/json or Application/xml”

What is a Swagger in Web API?

“Swagger is the most common template that is used in the Web API. This template is used to check the response of an API for different methods that a particular API supports. You just need to click on the verb (GET or PUT), specify tokens, body or payload (if applicable) and click on “try it out”.

Before implementation, every developer will provide you the swagger link on which you can superficially test the API. If not, the same can be achieved using a tool called POSTMAN.”

How can you make sure that Web API returns JSON data only?

A.In the header portion, you have to pass the value “application/json”.

If 200 is for all successful operation then why do we have 201 Response Codes?

“This is a tricky question. As we know, all the HTTP response codes in Web API can be manipulated by the developer and it all depends on the App Dev as how they want to configure the response codes.

Thus, you can have 200 or 201 for all successful operations. In general, 200 stands for a successful operation and 201 for the successful creation of a record.”

What parameters can you pass in the URL of the API? Can GET and POST use the same URL?

“There are a few parameters that you can pass in your URL to define the complete end-point. These are context keys, document keys or anything that facilitate the API to hit the exact endpoint.

For example, We have to hit the document “test” on Presto with the use of the context key com.express.presto.

In such a case, our URL happens to be https://www.presto.com but the complete end-point will look like

In this way, we can be sure that the endpoint will hit the test document using a specified context key.

Yes, GET and POST will have to use the same endpoint. If you don’t use the same endpoint, then it will be like you are creating a record in one URL and retrieving something else from the other URL and this won’t make any sense.”

Which library is used by the testers and developers to develop automated tests and create testing tools?

A.TestAPI is a library (utility) that is used to create automated tests and testing tools using algorithms.

What is a multilingual website?

Any website which supports multiple languages is called multilingual websites. The content of these websites are in different languages and can be converted into multiple languages. Some popular multilingual websites include Msn, Facebook, etc.

Define Web Services in ASP.net.

Web Services are the software services that serve from one machine to another using a network. These services make use of XML and provide SSL and WSS for data transmission.

What is the difference between Server.Transfer and Response.Redirect?

As we know, both Server.Transfer and Response.Redirect are used to facilitate the users to navigate from one page to the other during page execution. The major difference between them is that in Server.Transfer (as the name suggests), the transfer is done by the server and in Response.Redirect, it is done by the browser.

What are Session State Modes? List some of the important Session State Modes of ASP.net.

“Session state is something in which the session object stores information about any particular user logged into the system. This session information can be the user id or password, details about the user’s last login, last activity and so on.

This session state comes up with different storage options. Again, each option is handled by the value in the session state mode.

Important Session State Modes

State Server Mode: Stores session state in ASP.Net State Service. Session State does not hamper by the restart of the application in a particular region.
InProc Mode: A default mode in which the session state is stored in memory on the Web Server.
SQL Server Mode: Session State is stored in SQL Server Database. It is the same as State Server in preserving the session state even though the application restarts.
Custom Mode: Session state is stored in a custom storage provider. It (Custom Storage Provider) can be configured by the user.
Off Mode: This enables the offline mode. The Session State is disabled in this mode.”

What are SQL Notifications and SQL Invalidations?

“SQL notifications are the notifications that trigger when there is any change in the data which is copied in the cache.

SQL invalidation is something (you can call it a parser) that invalidates promptly when it finds any change in the data that is in the database against the copied data in the cache.”

What are Directives in ASP.Net? List down all the Important Directives.

“Directives are the instructions that are used to describe how .aspx pages will be processed by the framework. Different directives come with different options or attributes and easily provide class names, their descriptions or the files’ names of the code-behind class for any specific page.

It starts with <%@ and ends with %>.

The syntax is:

<%@[DirectiveType][Attributes or Options]%>
Important Directives:

@Page
@Assembly
@Control
@Master
@MasterType
@Implements
@Import
@Reference
@PreviousPageType
@OutputCache
@Register”

What are the Differences between Code-Behind and Code Inline?

“Code Behind is the code written in a separate class file whereas Code Inline is the code written inside an ASP.Net Web Page.
Code Behind has an extension .aspx.cs or .aspx.vb whereas Code Inline (as it is inside ASP.Net) has an extension .aspx only. Code Inline is written inside

What is Query String in ASP.Net?

“Query String is a string (collection of characters) that is passed on any web browser as a part of the address or URL. This is often separated by a question mark (?).

The syntax of the query string is Request.QueryString(variable)[(index).count]”

What is the file through which you can customize your ASP.Net Application?

web.config is the file through which we can customize our application in ASP.Net such as applying new themes, resizing images or cropping images.

Write a code for sending an email from ASP.Net Application.

” Writing a code snippet is very common in both ASP.net as well as Selenium interviews. For Selenium, we have already discussed how to send an email.

Below are the explanation and the code for sending an email from the ASP.Net application.

Explanation

In the below program, we are creating an object for MailMessage. Thereafter, we are specifying the sender and recipient email addresses. Then, we are specifying the subject line as Software Testing.

Later, we are drafting the body of the email which is then sent with the use of a Simple Mail Transfer Protocol through the localhost server.

Code With Comments

MailMessage mail = new MailMessage (); //creating an obj for MailMessage

mail.From = “xyz@xyz.com””; //specifying the sender mail id
mail.To = “”abc@abc.com””; //specifying the recipient mail id
mail.Subject = “”Software Testing””; //specifying the subject
mail.Body = “”Hi, Sending an email””; //drafting the body of the email
SmtpMail.SmtpServer = “”localhost””; //sending through the localhost server
SmtpMail.Send (mail); //passing the attribute “mail” in the Smtp.Send()”

How do you store a value in ViewState and Retrieve them?

“As we know, ViewState stores the value of the page and the user inputs on a Page.

Following is the example of how we store the value in ViewState and retrieve it.

ViewState[“emp”]=”Saket Saurav”; // Store the value in ViewState

string value=ViewState[“emp”].ToString(); //Retrieve information”

What is the Parent Class of all the Web Server control?

The parent class of all Web Server control is “System.Web.UI.Control”.

What is the Life-Span of the items in the View State?

The life span of the items in the View State depends on the life of the current page. They exist as long as the current page exists.

Web API Interview Questions Part 2

 

How to register exception filter globally?

“It is possible to register exception filter globally using following code-

GlobalConfiguration.Configuration.Filters.Add(new

MyTestCustomerStore.NotImplExceptionFilterAttribute());”

Explain what is REST and RESTFUL?

“REST represents REpresentational State Transfer; it is entirely a new aspect of writing a web app.

RESTFUL: It is term written by applying REST architectural concepts is called RESTful services. It focuses on system resources and how the state of the resource should be transported over HTTP protocol.”

Give me one example of Web API Routing?

“Config.Routes.MapHttpRoute(

name: “”MyRoute,””//route name

routeTemplate: “”api/{controller}/{action}/{id}””,//as you can see “”API”” is at the beginning.

defaults: new { id = RouteParameter.Optional }

);”

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”

How can you pass multiple complex types in Web API?

“Two methods to pass the complex types in Web API –

Using ArrayList and Newtonsoft array”

Write a code for passing ArrayList in Web API?

“ArrayList paramList = new ArrayList();

Category c = new Category { CategoryId = 1, CategoryName =“MobilePhones”};

Product p = new Product { Productcode = 1, Name = “MotoG”, Price = 15500, CategoryID = 1 };

paramList.Add(c);

paramList.Add(p);”

Name the tools or API for developing or testing web api?

“Testing tools for web services for REST APIs include:

Jersey API
CFX
Axis
Restlet”

State differences between MVC and WebAPI

“MVC framework is used for developing applications which have User Interface. For that, views can be used for building a user interface.

WebAPI is used for developing HTTP services. Other apps can also be called the WebAPI methods to fetch that data.”

GlobalConfiguration.Configuration.Filters.Add (new MyTestCustomerStore.NotImplExceptionFilterAttribute());”

Explain method to handle error using HttpError in Web API?

In WEB API HttpError used to throw the error info in the response body. “CreateErrorResponse” method is can also use along with this, which is an extension method defined in “HttpRequestMessageExtension.”

Web API uses which library for JSON serialization?

Web API uses Json.NET library for JSON serialization.

What is Exception handling?

“Exception handling is a technique to handle runtime error in the application code. In multiple ways we can handle the error in ASP.NET Web API, some of them are listed below:

HttpResponseException

HttpError

Exception Filters etc.”

In How many ways we can do Web API Versioning?

“We can do Web API Versioning in the following ways:

URI

Query String Parameter

Custom Header Parameter

Accept Header Parameter

How Web API Routes HTTP request to the Controller ASP.NET MVC?

In ASP.NET Web API, HTTP request maps to the controller. In order to determine which action is to invoke, the Web API framework uses a routing table.

What is Basic HTTP Authentication?

Basic HTTP Authentication is a mechanism, where the user is authenticated through the service in which the client pass username and password in the HTTP Authorization request headers. The credentials are formatted as the string “username:password”, based encoded.

What is the use of Authorize Attribute?

Web API provided a built-in authorization filter, i.e. Authorize Attribute. This filter checks whether the user is authenticated or not. If not, the user will see 401 Unauthorized HTTP Status Code.

What is Media-Type Formatter in ASP.NET Web API?

Media-Type formatter is an abstract class from which JsonMediaTypeFormatter (handle JSON format) and XmlMediaTypeFormatter (handle XML format) class derived from. Media-Type formatter are classes responsible for serializing the response data in the format that the client asked for.

What is Content Negotiation in Web API?

“Content Negotiation is the process of selecting the best representation for a given response when there are multiple representations available. Two main headers which are responsible for the Content Negotiation are:

Content-Type

Accept

The content-type header tells the server about the data, the server is going to receive from the client whereas another way to use Accept-Header, which tells the format of data requested by the Client from a server. In the below example, we requested the data from the server in JSON format.”

What is Parameter Binding in ASP.NET Web API?

“When Web API calls a method on a controller, it must set the values for the parameters, this particular process is known as Parameter Binding. By Default, Web API uses the below rules in order to bind the parameter:

FromUri: If the parameter is of “Simple” type, then Web API tries to get the value from the URI. Simple Type includes.Net Primitive type like int, double, etc., DateTime, TimeSpan, GUID, string, any type which can be converted from the string type.

FromBody: If the parameter is of “Complex” type, then Web API will try to bind the values from the message body.”

What is Request Verbs or HTTP Verbs?

“In RESTful service, we can perform all types of CRUD (Create, Read, Update, Delete) Operation. In REST architecture, it is suggested to have a specific Request Verb or HTTP verb on the specific type of the call made to the server. Popular Request Verbs or HTTP Verbs are mentioned below:

HTTP Get: Used to get or retrieve the resource or information only.

HTTP Post: Used to create a new resource on the collection of resources.

HTTP Put: Used to update the existing Response

HTTP Delete: Used to Delete an existing resource.”

What are the RESTful Services?

“REST stands for the Representational State Transfer. This term is coined by the Roy Fielding in 2000. RESTful is an Architectural style for creating loosely couple applications over the HTTP. In order to make API to be RESTful, it has to adhere the around 6 constraints that are mentioned below:

Client and Server Separation: Server and Clients are clearly isolated in the RESTful services.

Stateless: REST Architecture is based on the HTTP Protocol and the server response can be cached by the clients, but no client context would be stored on the server.

Uniform Interface: Allows a limited set of operation defined using the HTTP Verbs. For eg: GET, PUT, POST, Delete etc.

Cacheable: RESTful architecture allows the response to be cached or not. Caching improves performance and scalability.

Code-On-Demand

Layered System”

What is the difference between ASP.NET MVC application and ASP.NET Web API application?

ASP.NET MVC is used to create a web application which returns both data as well as View whereas Web API is used to create HTTP based Services which only returns data not view. In an ASP.NET MVC application, requests are mapped to Action Methods whereas in the ASP.NET Web API request is mapped to Action based on the Action Verbs.

How can you return JSON from Web API Service irrespective of the Accept header value?

We can easily return JSON from Web API Service irrespective of the Accept header value by removing the XmlFormatter from the Register() method of WebApiConfig.cs file, which is present inside the App_Start folder. Use the following piece of code to remove XmlFormatter completely. It will always return data in JSON format irrespective of the Accept header value in the client request.

How can we unit test the Web API?

“We can use the Fiddler tool to unit test the Web API. Follow the steps given below and do the setting in the Fiddler tool:

Compose Tab -> Enter Request Headers -> Enter the Request Body and execute.”

What do you understand by Internet Media Types?

“The Internet Media Type is a file identification mechanism on the MIME encoding system. It is also known as the “”MIME type.”” It has become the de facto standard for identifying content on the Internet.

For example, suppose we receive an email from a server with an attachment, then the server embeds the media type of the attachment in the message header. So, the browser can launch the appropriate helper application or plug-in.”

What are some commonly seen HTTP Status Codes?

“Following is the list of some commonly seen HTTP Status Codes:

200 (Request is Ok)
201 (Created)
202 (Accepted)
204 (No Content)
301 (Moved Permanently)
400 (Bad Request)
401 (Unauthorized)
403 (Forbidden)
404 (Not Found)
500 (Internal Server Error)
502 (Bad Gateway)
503 (Service Unavailable) etc.”

What are the different HTTP methods used in Web API?

“Following are the different types of HTTP methods used in Web API. We can use them according to the requirements.

GET: The GET method is used to retrieve the information from the respective server using a given URI.
HEAD: The HEAD method is the same as the GET method, but it is used to transfer the status line and header section.
PUT: The PUT method is used to update values, and it can replace all current resources with the uploaded content.
POST: A POST method is a request, and it is used to send data to the respective server.
DELETE: The DELETE method is used to delete or remove all current resources given by a URI.
OPTIONS: This method is used to describe the communication options for the target resource.
CONNECT: The CONNECT method is used to establish a tunnel to the server identified by a given URI.
TRACE: The TRACE method is used to perform a message loop-back test along the target resource path.”

Who can use or consume Web API?

Any client which supports HTTP verbs such as GET, PUT, DELETE, POST etc., can use or consume Web API. Web API services don’t need any configuration, so it is very easy to consume them by any client. Even portable devices like mobile devices can easily consume them, and it is surely the biggest advantages of this technology.

How many ways are you to do Web API Versioning?

“Following are the several ways to do Web API Versioning:

URI
Query String Parameter
Custom Header Parameter
Accept Header Parameter”

What is Web API Versioning, and why is it used?

Web API Versioning is a technique in which Web API is arranged to cope with the business changes, and the API will not impact the client that is using/consuming the existing API. As we know, multiple clients can consume the Web API at a time, so Web API versioning is necessary and required as the business grows, and business requirement changes with the time.

What do you understand by Exception handling in Web API?

“Exception handling is a technique used to handle runtime error in the application code. There are several ways that we can use to handle the error in ASP.NET Web API. Following is a list of some of them:

HttpResponseException
HttpError
Exception Filters etc.”

How can we handle an error using HttpError in Web API?

In Web API, the HttpError method is used to throw the response body’s error info. Along with this, the “CreateErrorResponse” method can also be used, which is an extension method defined in “HttpRequestMessageExtension.”

How can the Web API route the HTTP request to the Controller ASP.NET MVC?

In ASP.NET Web API, an HTTP request is used to map to the controller. The Web API framework uses a routing table to determine which action is to invoke.

How can you pass an ArrayList in Web API?

“The following example shows the code how we can pass an ArrayList in Web API:

ArrayList paramList = new ArrayList();
Category c = new Category { CategoryId = 1, CategoryName =””MobilePhones””};
Product p = new Product { Productcode = 1, Name = “”MotoG””, Price = 15500, CategoryID = 1 };
paramList.Add(c);
paramList.Add(p); “

What do you understand by basic HTTP Authentication?

Basic HTTP Authentication is a mechanism that is used for user authentication. Here, users are authenticated through the service in which the client passes username and password in the HTTP Authorization request headers. The credentials are formatted as the string “username:password,” based on encoded.

Is it possible to pass multiple complex types in Web API?

“Yes, we can easily pass multiple complex types in Web API by using the following two methods:

Using ArrayList
Using Newtonsoft array”

What is Authorize Attribute? What is its use?

Web API provides a built-in authorization filter known as Authorize Attribute. This filter is used to check whether the user is authenticated or not. If not, the user will see 401 Unauthorized HTTP Status Code.

How can you restrict access methods to specific HTTP verbs in Web API?

“It is very easy to implement access restrictions in Web API with Attributes’ help (like HTTP verbs). We can do it by defining HTTP verbs as an attribute to restrict access.

For example,

[HttpPost]
public void Method1(Class obj)
{ “

What are the several new features that come with ASP.NET Web API 2.0?

“Following are the latest new features of ASP.NET Web API framework v2.0:

Attribute Routing
Open Web Interface NET
Cross-Origin Resource Sharing
External Authentication
HttpActionResult
Web API OData”

What do you understand by a Media-Type Formatter in ASP.NET Web API?

“The Media-Type formatter is an abstract class acting as a parent class of JsonMediaTypeFormatter and XmlMediaTypeFormatter. These two classes, JsonMediaTypeFormatter (which is used to handle JSON format) and XmlMediaTypeFormatter (which is used to handle XML format), are derived from the Media-Type formatter.

The Media-Type formatter classes are also responsible for serializing the response data in the client’s format.”

What is Content Negotiation in Web API?

“Content Negotiation is the process of selecting the best representation for a given response from a set of various multiple representations available. Following are the two main headers that are responsible for the Content Negotiation:

Content-Type: The content-type header is used to specify the server about the data; the server will receive from the client.
Accept: Another way for Content Negotiation is to use Accept-Header. It is used to specify the format of data requested by the client from a server.”

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