Web API Interview Questions and Answers

Q1. What is Web API?
An application programming interface (API) is a set of subroutine definitions, data structures, object classes, protocols, and tools for building software and applications.
To put it in simple word, API is some kind of interface which has a set of functions that allow programmers to access specific features or data of an application, operating system or other services.
Web API as the name suggests, is an API over the web which can be accessed using HTTP protocol. It is a concept and not a technology. We can build Web API using different technologies such as PHP, Java, .NET etc. For example, Twitter’s REST APIs provide programmatic access to read and write data using which we can integrate twitter’s capabilities into our own web application.

Q2. What is REST?
REpresentational State Transfer. It describes how one system can communicate state with another. One example would be the state of a product (its name, description etc) represented as XML, JSON, or plain text. The generalised idea of state is termed a resource.

Q3. What are the Advantages of using Web APIs
The advantages of using an Application Programming Interface, or API, in Web development are based on an API’s ability to interact with Web pages.
1. External Database Access/Information sharing : APIs provide ability to website visitors to access remote, password-protected databases. Your API password and username authorizes permission for information or data to be exchanged between your website and the APIs database-driven resources. An API’s functions include connecting, fetching and closing the access to its affiliated server as necessary.
2. Convenience : Analyze the areas of your website’s services to discover features that an API can handle. The right API can function a lot like outsourcing in the sense that you can use an API to manage parts of an online business. Tasks that are helpful but not essential to the core of your business can be addressed by an API; for example, you can use an API to handle tasks on your behalf so that you can focus on the most critical functions of your business.
3. Security Protection : Some API applications access additional servers as necessary. Protection from security-related vulnerabilities is an API-specific advantage worth investigating as you choose an API for your website. An API that won’t require you to expand trust to multiple remote servers can maintain your site’s security. Examine the security risks associated with an API of interest before incorporating one into your site.
4. Automation : The cross platform applications are linked with each other using the API and automate their process communication to avoid manual interventions.
5. Extended ability to customize user experience : with an API an application layer can be created which can be used to distribute information and services to new audiences which can be personalized to create custom user experiences.
6. Efficiency : when access is provided to an API, the content generated can be published automatically and is available for every channel. It allows it to be shared and distributed more easily.
7. Integration :APIs allow content to be embedded from any site or application more easily. This guarantees more fluid information delivery and an integrated user experience.

Q4. What are the alternatives to REST and how does REST compare with them
This is akin to asking “How RESTful is my approach?” Use the following list (summarised from the Richardson Maturity Model as described by Martin Fowler):
Level 0 – The swamp of POX :Use POST for everything (reads, writes, deletes). This is SOAP, POX, RPI etc. You’re just using HTTP as a tunnel for your own protocol. You target a single endpoint that does everything based on the contents of the request body.
Level 1 – Resources : Use POST for everything. Target multiple endpoints designed to serve up information about a particular thing. You’ve just discovered resources.
Level 2 – HTTP verbs : Use HTTP verbs against resources. Now you’re GETing it. POST is to create, PUT is to overwrite, OPTIONS for available operations, DELETE to, well, delete the resource. As a result of the use of these verbs different HTTP status codes start to become more relevant (202 ACCEPTED anyone?).
Level 3 – Hypermedia control (HATEOAS) : At this point you make the final leap and introduce hypermedia as a flow control mechanism. A REST client needs no prior knowledge about how to interact with any particular application or server beyond a generic understanding of hypermedia. This can be communicated in HTTP through the Content-Type header field. Text formats include AtomPub and (more concise) HAL, while HyperAudio works well for audio streams (see SoundCloud et al)

Q5. What is GET, POST, PUT and DELETE?
An HTTP request is a class consisting of HTTP style requests, request lines, request methods, request URL, header fields, and body content. The most common methods that are used by a client in an HTTP request are as follows:-
GET:- Used when the client is requesting a resource on the Web server..
POST:- Used when the client is sending information or data to the server—for example, filling out an online form (i.e. Sends a large amount of complex data to the Web Server).
PUT:- Used when the client is sending a replacement document or uploading a new document to the Web server under the request URL.
DELETE:- Used when the client is trying to delete a document from the Web server, identified by the request URL.

Q6. What position does it occupy in a web architecture ecosystem?
REST is commonly associated with the web services interface since HTTP is by far the most common carrier protocol. In the 7-layer model it exists at the application layer. However, see the next section.

Q7. What is difference between PUT and POST?
POST is used to create a new entity. “Post” means “after”; if you have a collection of entities and you tack a new one onto its end, you have posted to the collection. You can’t post an existing entity, and it’s common (though not always required) to use the collection’s URI to post. (E.g. you would create a new Quora user named Noah by POSTing to https://quora.com/users as opposed to https://quora.com/users/noah.)
PUT is used to set an entity’s information completely. PUTting is similar to POSTing, except that it will overwrite the entity if already exists or create it otherwise. You could use a PUT to write a user to your database that may already be in it.

Q8. Explain Web API Routing?
Web API routing is similar to ASP.NET MVC Routing. It routes an incoming HTTP request to a particular action method on a Web API controller.
Web API supports two types of routing:

  1. Convention-based Routing
  2. Attribute Routing

Q9. How tightly (or loosely) it is coupled with protocol?
REST is not HTTP. It uses HTTP because in its most general form REST exists to assist a machine in mapping the concept of a verb against an arbitrary collection of nouns. HTTP contains a useful set of generic verbs (GET, PUT, PATCH etc) that can applied to arbitrary nouns expresssed as URIs using HTTP e.g. GET http://example.org/Product(54).

Q10. What is HttpStatusCode? Any other ?
var statusCodes = new List<HttpStatusCode>()
{
HttpStatusCode.BadGateway,
HttpStatusCode.GatewayTimeout,
HttpStatusCode.HttpVersionNotSupported,
HttpStatusCode.InternalServerError,
HttpStatusCode.NotImplemented,
HttpStatusCode.ServiceUnavailable
};
if (statusCodes.Contains(response.StatusCode))
throw new HttpRequestException(“Blah”);

Q11. Can we create SOAP based message using Web API?
We have a server which has several types of api (custom XML API based on httplistener, SOAP API based on WCF and REST API based on WEB API). We want to move all API’s to WEB API (there are many reasons) and it should be backward compatible.
One of the reason to support url structure: services/service1. services/service2. And in this case it should be on one port. It is intranet application which is distributed to multiple customers and it should be easy to deploy, install. So, we can not have a long configuration on customer side (proxing and otherts).

Q12. What are the Advantages of Using ASP.NET Web API?
If your project clients needs data in multiple formats (json,xml,csv) or have chance to change in future Wep Api needs minimal configuration comparing to mvc. Wep Api returns data to client according to content negotiation (if client needs xml returns xml,if json return json according to request header ) but in mvc you need more code to satisfy that.You have to explicitly specify data format when writing action methods.(JsonResult,ActionResult,XmlResult)
Wep Api gives you more meaningful idea about what you are doing when you look at the code later.Comparing method signatures; public List<Student> Get() has more meaning than public JsonResult Index().

Q13. Difference between Web API 1.0 and Web API 2.0?
WebAPI and WebAPI 2
Actually WebAPI 2.0 is enhanced feature of WebApi there is no difference between this two. In version 2.0, the Web API framework has been enhanced to support the following features:

  • IHttpActionResult return type
  • A new Routing Attribute
  • Support for Cross-Origin requests using CORS
  • Securing ASP.NET Web API using OAuth 2.0
  • Support for $expand, $select in OData Service

Q14. Which Features are Introduced in ASP.NET Web API 2.0?
In its simplest form, a Web API is an API over the web (HTTP). ASP.NET Web API is a framework that allows you to build Web API’s, i.e. HTTP-based services on top of the .NET Framework using a convention based and similar programming model, as that of ASP.NET MVC. These services can then be used in a broad range of clients, browsers and mobile devices.
Two versions of the ASP.NET Web API framework have been released so far, with Web API 2.0 being the latest one. In this article, we will explore some of the new features introduced in ASP.NET Web API 2.0.

Q15. Serialization and Deserialization in Web API?
public interface
IHttpMessageSerializer
{
void Serialize(HttpResponseMessage response, Stream stream);
void Serialize(HttpRequestMessage request, Stream stream);
HttpResponseMessage DeserializeToResponse(Stream stream);
HttpRequestMessage DeserializeToRequest(Stream stream);
}
public class MessageContentHttpMessageSerializer : IHttpMessageSerializer
{
private bool _bufferContent;
public MessageContentHttpMessageSerializer() : this(false)
{

}
public MessageContentHttpMessageSerializer(bool bufferContent)
{
_bufferContent = bufferContent;
}
public void Serialize(HttpResponseMessage response, Stream stream)
{
byte[] assuranceBuffer = null;
if (_bufferContent && response.Content != null)
assuranceBuffer = response.Content.ReadAsByteArrayAsync().Result; // make sure it is buffered
var httpMessageContent = new HttpMessageContent(response);
var buffer = httpMessageContent.ReadAsByteArrayAsync().Result;
stream.Write(buffer, 0, buffer.Length);
}
public void Serialize(HttpRequestMessage request, Stream stream)
{
byte[] assuranceBuffer = null;
if (_bufferContent && request.Content != null)
assuranceBuffer = request.Content.ReadAsByteArrayAsync().Result; // make sure it is buffered
var httpMessageContent = new HttpMessageContent(request);
var buffer = httpMessageContent.ReadAsByteArrayAsync().Result;
stream.Write(buffer, 0, buffer.Length);
}
public HttpResponseMessage DeserializeToResponse(Stream stream)
{
var response = new HttpResponseMessage();
var memoryStream = new MemoryStream();
stream.CopyTo(memoryStream);
response.Content = new ByteArrayContent(memoryStream.ToArray());
response.Content.Headers.Add(“Content-Type”, “application/http;msgtype=response”);
return response.Content.ReadAsHttpResponseMessageAsync().Result;
}
public HttpRequestMessage DeserializeToRequest(Stream stream)
{
var request = new HttpRequestMessage();
var memoryStream = new MemoryStream();
stream.CopyTo(memoryStream);
request.Content = new ByteArrayContent(memoryStream.ToArray());
request.Content.Headers.Add(“Content-Type”, “application/http;msgtype=request”);
return request.Content.ReadAsHttpRequestMessageAsync().Result;
}
}

Q16. Are there easy way for implementation SOAP service on web api?
At first look should be easy way to parse httprequest to typed soap envelope (based on existed contract) and serialize a answer. Of course, there many actions and data types in contract. PS: I do not want to look into servicestack:)
Update:The problem I described above can be fixed by proxing http request to soap service (It can work only with basichttpbinding without security. If WCF service require NTLM authentication it won’t work):
[HttpPost]  public async Task<
IHttpActionResult>
SoapAction() {
var httpClient = new HttpClient();
var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, “http://localhost:8111/soap”)
{
Content = this.Request.Content
};
foreach (var header in this.Request.Headers)
{
httpRequestMessage.Headers.Add(header.Key, header.Value); }
var responseMessage= await httpClient.SendAsync(httpRequestMessage).ConfigureAwait(false);
return ResponseMessage(responseMessage);
}

But I still want to know are there any SOAP parser in C# because my server supports NTLM authentication.

Summary
Review Date
Reviewed Item
Good work. Recommended to prepare from this site
Author Rating
51star1star1star1star1star