Web api scenario based interview questions

Web API Interview Questions: Web API is an important application programming interface that enables web services over a broad range of browsers and devices such as tablets, mobile phones, etc. It is of significant importance for its lightweight and simpler services as well as being able to be used as a standalone web service application.

If you are a student of Web API or a professional who is developing their competence in this framework, you already know the importance of having a reliable resource of Web API interview questions. As the focus of Web API is practical, any collection of questions has to address the application of Web API in practical scenarios. These interview questions can also help you prepare for your dream job in this field.

REST (Common Web API Testing interview questions)
  • What is REST? …
  • What is a RESTFul Web Services? …
  • What is a “Resource” in REST? …
  • What is the most popular way to represent a resource in REST? …
  • Which protocol is used by RESTful Web services? …
  • What are some key characteristics of REST? …
  • What is messaging in RESTful Web services?

REST API interview questions and answers | REST API questions and answers for experienced |

Web API Basic 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 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.

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

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

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

WCF (Windows Communication Foundation): It is a framework used for developing SOAP (Service-oriented applications). This framework is used for developing, configuring, and deploying, or implementing network-distributed services.Web API: It is an application programming interface for both web browsers and web servers. Browser API simply extends or increases the functionality of web browsers whereas Server API simply extends or increases the functionality of web server.

Web API WCF
It is used to develop both SOAP-based services and RESTful services. It is used to deploy only SOAP-based services.
It supports various MVC features such as routing, model binding, etc. It does not support any MVC features.
It only supports HTTP protocol. It supports various protocols such as HTTP, UDP, custom transport.
It is considered best for developing RESTFUL services. It supports only limited RESTFUL services.
It is good when one wants to expose an expensive range of clients such as iPhones, browsers, mobile phones, tablets, etc. It is good for creating services that uses expedite transport channels such as TCP, UDP, Named pipes, etc.
It offers support for UTF-8 encoding format. It offers TEXT, Binary encoding support, MTOM (Message Transmission Optimization Mechanism), etc.

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

6. What is different between REST API and RESTful API?

REST (Representation State Transfer) API:  It is basically an architectural style that makes productive use of existing technology and protocols of the web. It is a set of rules that developers need to follow when they develop their API or services that are scalable. It is used with HTTP protocol using its verbs such as GET, DELETE, POST, PUT.
RESTful API: It is simply referred to as web services executing such as architecture.

REST API RESTful API
REST is an architectural pattern used for creating web services. RESTful API is used to implement that pattern.
The data format of REST is based on HTTP. The data format of RESTful is based on JSON, HTTP, and Text.
Working of URL is based on request and response. Working of RESTful is based on REST applications.
It is more user-friendly and highly adaptable to all business enterprises and IT. It is too flexible.
It is required to develop APIs that allow interaction among clients and servers. It simply follows REST infrastructure that provides interoperability among different systems on the whole network.

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

8. When do we need to choose ASP.NET Web API?

In today’s hyper-connected digital world, we are moving web-based services towards mobile applications. That means we need an API that is lightweight, secure, safe and compatible with these smart devices. The ASP.Net Web API is a framework that fulfils all these requirements for building HTTP services consumed by a vast array of clients including browsers and modern devices such as mobile phones, tablets, etc.

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

10. What are the technical benefits of Web API?

Web API has a few technical benefits:

    • Easy configuration
    • Separate from UI development
    • Simple business logic testing with advanced tools such as rest-client
    • Lightweight architecture, suitable for devices with low bandwidth
    • Based on HTTP, making it easier to define
    • Supported by many MVC features, like action results, model binders, etc.
    • Comes with descriptive message headers that determine the content type, and headers that explain how to secure it, cache information, etc.
    • Performs standard CRUD (Create Read Update Delete) operations via the HTTP forms, such as GET, PUT, POST, and DELETE
    • Enables you to develop full-featured REST services
    • API service interface consists of URL patterns and HTTP methods
    • Helps you access non-SOAP-based services, such as XML or JSON strings

11. What are the disadvantages of Web API?

Here are some disadvantages of Web API:

  • Web API incurs costs in terms of development time and maintenance.
  • Web API makes your website vulnerable to cyber attacks.
  • API usage isn’t always predictable.
  • You need to have the technical knowledge to construct APIs.
  • The API can crash while testing, resulting in increased maintenance costs.

12. Explain the difference between the Web API and WCF.

WCF is a framework for creating a distributed and interoperable application. It is also suitable for building service-oriented connected applications to transmit asynchronous data from one service point to another.

Web API is an interface for web browsers and web servers. Browser API simply extends the functionality of web browsers, whereas Server API simply extends the functionality of web servers.

13. What are media type formatters?

Media type formatters are classes responsible for serialization data. Serialization involves translating data into a format that is easy to transmit and reconstruct later.

With serializing request/response data, Web API can efficiently understand the request data format and send data in a format expected by the client. It specifies data exchanged between the client and the server in an HTTP response or request.

Media Type Formatter Class Description
JsonMediaTypeFormatter Handles JSON format
XmlMediaTypeFormatter Handles XML format
FormUrlEncodedMediaTypeFormatter Handles HTM form URL-encoded data
JQueryMvcFormUrlEncodedFormatter Handles model-bound HTML form URL-encoded data

14. Which protocol is supported by Web API?

Web API supports the HTTP protocol.

15. What are JSON and XML?

XML (Extensible Markup Language) is designed for storing and transferring data in a structured format. It works similar to the HTML but is more flexible as the users can create their custom tags.

On the other hand, JSON (JavaScript Object Notation) is a lightweight format for storing and transferring data. It has text-based formatting for representing the structured data, making it easier to understand and faster to use.

16. What are different filters available in Web API?

Filters allow you to add extra logic at different levels of the Web API framework. The following are the different filters in Web API:

  • Authentication filter: This filter takes care of the authentication and authorization HTTP requests. For example, checking the identity of the users.
  • Authorization filter: This filter checks user authenticity and invokes the HTTP status code 401 if the user isn’t authenticated.
  • AuthorizeAttribute: This is a built-in authorization filter.
  • Action filter: You can apply this filter to controller action or the entire controller. You can use it to add the logic before or after the execution of the controller action.
  • Exception filter: Handles all the unhandled exceptions thrown by controller actions in Web API.
  • Override filter: Excludes specific action methods from the global filters, and helps modify the behavior of other filters.

Web API Interview Questions and Answers for Experienced Candidates (Intermediate)

17. Explain error handling in Web API.

Web API offers various error handling classes:

  • HttpResponseException: Returns the HTTP status code mentioned in the exception Constructor.
  • HttpError: Returns the meaningful error code to the client using the HttpResponseMessage.
  • Exception filters: Caches the unhandled exceptions or errors generated in Web API and are useful when the controller action method throws the unhandled error.

18. Explain MVC and how it’s different from Web API.

MVC stands for Model, View, and Controller. Developers generally use it for developing model user interfaces. MVC keeps the data and the display separate and enables the developers to modify both without impacting each other.

The following points describe how MVC and Web API differ:

  • MVC is commonly used for developing applications that return both data and views. On the other hand, Web API generates HTTP services effortlessly that returns only data, and not view.
  • MVC uses action names to perform the tracing. Web API uses the HTTP services actions to perform the tracing.
  • The Web API returns the information in JSON, XML, and other formats. MVC returns the data in JSON format only.
  • Web API supports self-hosting and negotiation, while MVC does not.
  • The Web API helps create the RESTful services using the .Net Framework, while MVC does not support it.

ASP.NET Web API Interview Questions

19. What is ASP.NET Web API?

ASP.NET Web API is a framework and a perfect solution for developing RESTful applications on the .NET framework. Using the ASP.NET Web API framework, you can seamlessly create HTTP services to respond to a broad range of clients, including browsers and mobile devices.

Microsoft provides this framework for developing HTTP-based services on top of the .Net framework.

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

Here are some advantages of ASP.NET Web API:

  • Well-suited for creating RESTful applications on the .NET framework.
  • Works similarly to the HTTP using GET, POST, PUT, DELETE for performing CRUD actions.
  • A flexible option for creating Web API.
  • Supports routing.
  • Supports model binding, validation, Odata, etc.
  • Uses ApiExplorer for developing custom help and test pages.
  • Can seamlessly create non-SOAP-based services, such as XML, JSON, etc.

21. What is caching? What are a few different types of caching?

Caching involves temporarily storing information for quick reference. It contains all the frequently accessed files in its memory. Whenever you re-access those files, the cache memory shows you the files, rather than leading you to the actual website again and again.

A few different types of caching include:

  • Page caching
  • Fragment caching
  • Data caching

Web API Interview Questions for Beginners and Advanced

22. How to mention Roles and users using Authorize attribute in Web API?

// Restrict by Name
[Authorize(Users=”Shiva,Jai”)]
public class StudentController : ApiController{}
// Restrict by Role[Authorize(Roles=”Administrators”)]
public class StudnetController : ApiController{}

23. Can we apply constraints at the route level?

A: Yes, it can be applied.

[Route(“students/{id:int}”]

public User GetStudentById(int id) { … }

[Route(“students/{name}”]

public User GetStudentByName(string name) { … }

You can select the first route whenever the “id” segment of the URI is an integer. Or else, you can choose the second route.

24. How to enable attribute routing?

A: To enable attribute routing, MapHttpAttributeRoutes(); method can be called in the WebApi config file.

public static void Register(HttpConfiguration config)

{

// Web API routes

config.MapHttpAttributeRoutes();

// Other Web API configuration not shown.

}

25. How parameters get the value in Web API?

A: Parameters get value in Web API in the following way:

  • Request body
  • URI
  • Custom Binding

26. Why is the “api/” segment used in Web API routing?

A: “api/” segment is used to avoid collisions with ASP.NET MVC routing

27. Is it possible to have MVC kind of routing in Web API?

A: It is possible to implement MVC kind of routing in Web API.

28. Where is the route defined in Web API?

A: It is placed in the App_Start directory.

App_Start –> WebApiConfig.cs

routes.MapHttpRoute(

name: “myroute”,

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

defaults: new { id = RouteParameter.Optional }

);

29. How do you construct HtmlResponseMessage?

public class TestController : ApiController

A: To construct HtmlResponseMessage, you can consider the following way:

{

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;

}

}

30. What are the default media types supported by Web API?

A: The default media types that are supported by Web API are XML, form-urlencoded data, JSON, BSON. The other media types supported can be done by writing a media formatter.

31. What is the disadvantage of “Other Return Types” in Web API?

A: The major disadvantage of “Other Return Types” in Web API is that error codes like 404 errors will not directly be returned.

32. What is the namespace for IHttpActionResult return type in Web API?

A: System.Web.Http.Results namespace

33. Why is Web API important?

We have several other technologies similar to Web API yet it is the most important and preferred over others for several reasons –

  • Web API has the most lightweight architecture and provides an easy interface for websites and client applications to access data.
  • It uses low bandwidth. This makes it ideal for even small bandwidth devices, for instance, smartphones.
  • It can create non-SOAP-based HTTP services.
  • It can be consumed by a range of clients including web browsers, desktop and mobile applications.
  • Web API is based on HTTP which makes it convenient to define, consume or expose using REST-ful services.
  • It fits best with HTTP verbs for operations such as Create, Read, Delete or Update.
  • Web API is more useful from the business point of view and finds its applications in UI/UX to increase web traffic and interest in a company’s services or products.
  • It can support a plethora of text and media formats such as JSON, XML, etc.
  • It can also support Open Data (OData) protocol.
  • It is most suitable for the MVC pattern which makes it ideal for experienced developers in that pattern.
  • It can be easily built using technologies such as ASP.NET, JAVA, etc.
  • It is considered the best to create resource-oriented services.

34. Which .NET framework supports Web API?

The .NET framework version supported by Web API includes version 4.0 and above.

35. Which open-source library is supported by Web API for JSON serialization?

JSON.NET library is a high-performance JSON framework used for JSON serialization by Web API.

36. What are the advantages of using REST in Web API?

REST offers numerous advantages in Web API that include –

  • Lightweight architecture and easy to use
  • Offers flexibility
  • Allows less data transfer between client and server
  • Handles various types of data formats
  • Its lightweight architecture makes it optimal for use in mobile applications
  • Uses simple HTTP calls for inter-machine communication

37. When do we need to choose ASP.NET Web API?

In today’s hyper-connected digital world, we are moving web-based services towards mobile applications. That means we need an API that is lightweight, secure, safe and compatible with these smart devices. The ASP.Net Web API is a framework that fulfils all these requirements for building HTTP services consumed by a vast array of clients including browsers and modern devices such as mobile phones, tablets, etc.

38. What do you understand by TestApi in Web API?

TestAPi in Web API refers to a utility library that allows developers to create testing tools as well as automate tests for a .NET application.

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

The HttpError method is used in Web API to throw the response body’s error information. One can also use the “CreateErrorResponse” method along with this one.

40. Can we consume Web API 2 in the C# console application?

Yes. It is possible to consume Web API 2 in Console Application, MVC, Angular JS or any other application.

41. How to implement Basic Authentication in ASP.Net Web API?

Basic Authentication in ASP.Net Web API is one where the client will send a request using the word Basic with an Authorization header, followed by a base 64 encoded string.

The syntax for Basic Authentication –

Authorization: Basic username: password

42. Give an example of the parameter in Web API.

Parameters are used in Web API to determine the type of action you take on a particular resource. Each parameter consists of a name, value type and description that has the ability to influence the endpoint response.

You can use the query API to get information about various entities within a data source.

The Get Method employs multiple primitive parameters. For instance, the Get method needs id parameter to get product details –

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
public IHttpActionResult GetProductMaster(int id)
{
ProductMaster productMaster = db.ProductMasters.Find(id);
if (productMaster == null)
{
return NotFound();
}
return Ok(productMaster);
}
In the same way, the Post method will require complex type parameters to post data to the server.
public IHttpActionResult PostProductMaster(ProductMaster productMaster)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
db.ProductMasters.Add(productMaster);
db.SaveChanges();
return CreatedAtRoute(“DefaultApi”, new { id = productMaster.id }, productMaster);
}
Similarly PUT method will require primitive data type example for id and complex parameter i.e. ProductMaster class.
if (id != productMaster.id)
{
return BadRequest();
}
db.Entry(productMaster).State = EntityState.Modified;
try
{
db.SaveChanges();
}
catch (DbUpdateConcurrencyException)
{
if (!ProductMasterExists(id))
{
return NotFound();
}
else
{
throw;
}
}

FAQ

What is Cors in Web API interview questions?

CORS (Cross-origin resource sharing) is a technique that allows restricted resources on a web page to be requested from another domain outside the domain of which the first resource was served.

Does Web API supports to non SOAP based like XML or JSON?

WEB API supports any media format, even XML, JSON; while, WCF supports SOAP and XML format. ASP.Net Web API is ideal for building HTTP services, while WCF is perfect for developing service-oriented applications.

What is REST API in interview?

REST has a URI for accessing resources by means of a request-response pattern. AJAX uses XMLHttpRequest object to send requests to the server and the response is interpreted by the Javascript code dynamically. REST is an architectural pattern for developing client-server communication systems.

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *