A Beginner's Guide to Web APIs: How They Work and Why They Matter

Published on 31 December 2017 | by Santosh Kumar Tripathi

What is a Controller in .NET Core Web API?

Answer: A controller in .NET Core Web API is a class that handles HTTP requests and returns responses. It is derived from the ControllerBase class (or Controller if using MVC).


    [ApiController]
    [Route("api/[controller]")]
    public class MyController : ControllerBase
    {
     [HttpGet]
     public IActionResult Get() => Ok("Hello, World!");
    }

What is the difference between Controller and ControllerBase?

Answer: Feature Controller ControllerBase

Feature Controller ControllerBase
Inherits from ControllerBase ControllerBase
Supports Views ✅ Yes (for MVC) ❌ No (for API)
Use Case Web API + Views Web API only

What are the benefits of using the [ApiController] attribute?

Answer: The [ApiController] attribute provides:

  • Automatic Model Validation – Returns 400 Bad Request for invalid models.
  • Binding Source Inference – Auto-detects [FromQuery], [FromBody], etc.
  • Improved Error Handling – Provides clear error messages.
For Web APIs, use ControllerBase to avoid unnecessary dependencies on MVC-related features.

Why is the Web API important?

  • Provides an interface for websites and client applications to have access to data.
  • Can be used to access data from the database and save data back to the database.
  • Supports different text formats such as XML, JSON, etc.
  • Compatible with any type of browser and any type of device like mobile, desktop, web, etc.
  • Uses low bandwidth such as XML or JSON data, etc.(good for low bandwidth devices like smartphones)
  • Web API is more applicable from a UI/UX point of view., front end technologies can be changed easily.

What is Web API and why do we use it?

  • Web API is an Application Programming Interface.
  • It is a framework that helps us to build or deploy the services of HTTP.
  • An API that can be accessed over the Web using the HTTP protocol.
  • It is considered the best platform for revealing or uncovering data and services to various services.
  • 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 RESTful services and SOAP-based services.

What is the default return type of Web API?

IActionResult and it returns by default XMLtype data.

Which is lighter JSON or XML?

JSON is lighter because it requires fewer bytes.

What is the difference between Web API and WCF?

WCF (Windows Communication Foundation): A framework for developing SOAP (Service-oriented applications).

Web API: It is an application programming interface for both web browsers and web servers.

Web Service (ASMX) WCF WCF Rest Web API

It is based on SOAP and returns data in XML form.

It is also based on SOAP and returns data in XML form.

It supports XML, JSON and ATOM data formats.

It is used to develop both SOAP-based services and RESTful services.

Responses are formatted by Web API MediaTypeFormatter into JSON, XML or whatever format you want to add as a MediaTypeFormatter.

It supports only HTTP protocol.

It is the evolution of the web service(ASMX) and supports various protocols like TCP, HTTP, HTTPS, Named Pipes, and MSMQ.

To use WCF as a WCF Rest service you have to enable webHttpBindings.

This is the new framework for building HTTP services easily and simply. It only supports HTTP protocol.

It is not open source but can work that understands XML.

It is not open source but can be consumed by any client that understands XML.

Passing data through parameters using a WebGet needs configuration. The UriTemplate must be specified.

Web API is open source and an ideal platform for building RESTful services over the .NET Framework.

It can be hosted only on IIS.

It can be hosted in the application or on IIS or using Windows service.

It supports HTTP GET and POST verbs by [WebGet] and [WebInvoke] attributes respectively.

For other HTTP verbs do some configuration IIS to accept the request of that particular verb on .svc files

Unlike the WCF Rest service, it uses the full features of HTTP (like URIs, request/response headers, caching, versioning, and various content formats)

The main issue with WCF is its tedious and extensive configuration.

Also supports the MVC features such as routing, controllers, action results, filters, model binders, IOC container or dependency injection, and unit testing making it more simple and robust.

What chooses between WCF or WEB API?

WCF Web API

Choose WCF when you want to create a service that should support special scenarios such as one-way messaging, message queues, duplex communication etc.

Choose Web API when you want to create a resource-oriented service over HTTP that can use the full features of HTTP (like URIs, request/response headers, caching, versioning, and various content formats).

Choose WCF when you want to create a service that can use fast transport channels when available, such as TCP, Named Pipes, or maybe even UDP (in WCF 4.5), and you also want to support HTTP when all other transport channels are unavailable.

Choose Web API when you want to expose your service to a broad range of clients including browsers, mobiles, iPhones and tablets.

What is the difference between REST API and RESTful API?

To differentiate or compare these 2, you should know what REST is.

REST (REpresentational State Transfer) is an architectural style of development having some principles:

  • It should be stateless
  • It should access all the resources from the server using only the URI
  • It does not have inbuilt encryption
  • It does not have a session
  • It uses one and only one protocol - HTTP
  • For performing CRUD operations, it should use HTTP verbs such as to get, post, put and delete
  • It should return the result only in the form of JSON or XML, atom, OData etc. (lightweight data )

REST-based services follow some of the above principles and not all but RESTFUL services mean it follows all the above principles.

It is similar to the concept of :

  • Object-oriented languages support all the OOP concepts, examples: C++, C#
  • Object-based languages support some of the OOP features, for example, JavaScript, VB

Example: ASP Dot NET MVC 4 is REST-Based while Microsoft WEB API is RESTFul. MVC supports only some of the above REST principles whereas WEB API supports all the above REST Principles.

MVC only supports the following from the REST API

  • We can access the resource using the URI
  • It supports the HTTP verb to access the resource from the server
  • It can return the results in the form of JSON, or XML, that is the HTTPResponse.

However, at the same time in MVC

  • We can use the session
  • We can make it stateful
  • We can return video or image from the controller action method which violates the REST principles

That is why MVC is REST-Based whereas WEB API supports all the above principles and is RESTFul.

What are the advantages of using Rest in Web API?

  • Less data transfer between client and server.
  • Easy to use and lightweight.
  • Provides more flexibility.
  • It also handles and controls various types of calls, returning various data formats.
  • Best for use 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 the difference between REST and SOAP?

Unfortunately, there is a lot of misinformation and misconceptions around REST.

SOAP and REST can't be compared directly, since SOAP is a protocol (or at least tries to be) and REST is an architectural style. This is probably one of the sources of confusion around it since people tend to call REST any HTTP API that isn't SOAP.

The main difference between SOAP and REST is the degree of coupling between client and server implementations.

A SOAP client works like a custom desktop application, tightly coupled to the server. There's a rigid contract between client and server, and everything is expected to break if either side changes anything. You need constant updates following any change, but it's easier to ascertain if the contract is being followed.

A REST client is more like a browser. It's a generic client that knows how to use a protocol and standardized methods, and an application has to fit inside that. You don't violate the protocol standards by creating extra methods, you leverage the standard methods and create the actions with them on your media type. If done right, there's less coupling, and changes can be dealt with more gracefully.

A client is supposed to enter a REST service with zero knowledge of the API, except for the entry point and the media type. In SOAP, the client needs previous knowledge of everything it will be using, or it won't even begin the interaction. Additionally, a REST client can be extended by code-on-demand supplied by the server itself, the classical example being JavaScript code used to drive the interaction with another service on the client side.

REST is protocol-independent. It's not coupled to HTTP. Pretty much like you can follow an FTP link on a website, a REST application can use any protocol for which there is a standardized URI scheme.

REST is not a mapping of CRUD to HTTP methods.

REST is as standardized as the parts you're using. Security and authentication in HTTP are standardized, so that's what you use when doing REST over HTTP.

REST is not REST without hypermedia and HATEOAS(Hypermedia as the Engine of Application State). This means that a client only knows the entry point URI and the resources are supposed to return links the client should follow. Those fancy documentation generators that give URI patterns for everything you can do in a REST API miss the point completely. They are not only documenting something that's supposed to be following the standard, but when you do that, you're coupling the client to one particular moment in the evolution of the API, and any changes on the API have to be documented and applied, or it will break.

REST is the architectural style of the web itself. When you enter Stack Overflow, you know what a User, a Question and an Answer are, you know the media types, and the website provides you with the links to them. A REST API has to do the same. If we designed the web the way people think REST should be done, instead of having a home page with links to Questions and Answers, we'd have static documentation explaining that to view a question, you have to take the URI stackoverflow.com/questions/<id>, replace id with the Question.id and paste that on your browser. That's nonsense, but that's what many people think REST is.

This last point can't be emphasized enough. If your clients are building URIs from templates in the documentation and not getting links in the resource representations, that's not REST. Roy Fielding, the author of REST, made it clear in this blog post: REST APIs must be hypertext-driven.

With the above in mind, you'll realize that while REST might not be restricted to XML, to do it correctly with any other format you'll have to design and standardize some format for your links. Hyperlinks are standard in XML, but not in JSON. There are draft standards for JSON, like HAL.

Finally, REST isn't for everyone, and proof of that is how most people solve their problems very well with the HTTP APIs they mistakenly called REST and never venture beyond that. REST is hard to do sometimes, especially in the beginning, but it pays over time with easier evolution on the server-side, and the client's resilience to changes. If you need something done quickly and easily, don't bother about getting REST right. It's probably not what you're looking for. If you need something that will have to stay online for years or even decades, then REST is for you.

Explain media type formatters.

Answer: In web API, media type formatters are classes that are responsible for serialization data. It simply specifies the data format that is being transferred among the client and server in HTTP response or request and expected by the client.

Media Type Formatter Class

MIME Type

Description

JsonMediaTypeFormatter

application/json, text/json

Handles JSON format

XmlMediaTypeFormatter

application/xml, text/json

Handles XML format

FormUrlEncodedMediaTypeFormatter

application/x-www-form-urlencoded

Handles HTM form URL-encoded data

JQueryMvcFormUrlEncodedFormatter

application/x-www-form-urlencoded

Handles model-bound HTML form URL-encoded data

What are the main return types supported in the Web API?

  • Not have any specific data type.
  • The default is XML.

It can return data of any type depending on the business requirement and use case.

Which Open-source libraries are used by WEB API for JSON serialization?

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

What are XML and JSON?

Answer:

XML (Extensible Markup Language):

  • It is specially designed to store and transport data.
  • It is similar to HTML but is more flexible than HTML because it allows users to create their 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.

Who can consume Web API?

A large range of clients such as browsers, mobile devices, iPhones, etc., include or consume web API. It can also be consumed by any client that supports HTTP verbs such as GET, DELETE, POST, and PUT.

What are Web API filters?

This is covered in .Net Core MVC

How to handle errors in Web API?

This is covered in MVC/ .Net Core

How to register an exception filter globally?

This is covered in MVC/ .Net Core

Difference between MVC and Web API?

MVC

Web 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 and self-hosting.

It does not support content negotiation or self-hosting.

It is not able to build REST-full services.

It is very helpful in creating RESTful services.

It returns a view (HTML).

It returns REST responses.

What is ASP.NET Web API?

Web API in Microsoft is implemented over the ASP.Net

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

  • Provides the best platform for developing RESTful applications on the .NET Framework.
  • Works the same way that HTTP works with the help of HTTP verbs such as GET, POST, PUT, and DELETE for all crud operations.
  • Completely supports routing.
  • Supports model binding, validation, and Odata (Open Data Protocol) that allows the creation and consumption of RESTful APIs.
  • It can develop custom help and test pages with the 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 difference between ControllerBase and Controller class?

The Controller class derives from ControllerBase and adds some members that are only needed to support Views.

Drive your controller from ControllerBase when want to create a controller Web API Controller and from the controller when want to create a controller for an MVC application.

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

Answer:

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 wants to move to some other transport like TCP, NetTCP, MSMQ, etc. WCF also allows one-way communication or duplex communication.

What are the main return types supported in Web API?

It supports the following return types:

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

What is HttpConfiguration in Web API?

It is considered as the main class that includes different properties with the help of which one can override the default behaviour 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 a View from the 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?

Answer: Content negotiation is 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 on the server side. In simple words, it chooses the best media type formatters to return a response to an incoming request.

What parameters can be passed in the URL of the API?

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

What is the use of a Delegating Handler?

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?

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

Difference between HTTP GET vs HTTP Post?

HTTP GET

HTTP POST

GET is used to request data from specified resources and has no other effect.

This method is used to send data to a server to create or update resources.

Its parameters are included in the URL.

Its parameters are included in the body.

It carries a request parameter appended in the URL string.

It carries request parameters in the message body that make it a more secure way of sending data or information from the client to the server.

The request method using GET is cacheable.

The request method using POST is not cacheable.

GET requests are less safe than POST.

Post request is safer than GET.

There is a restriction on data type in the GET method and only ASCII characters are allowed.

There are no restrictions on data type in this method and binary data is also allowed.

Data is visible to everyone in the URL.

Data is not displayed in the URL. It is present in the payload.

Difference between HTTP PUT vs HTTP POST?

HTTP PUT

HTTP POST

PUT method requests for the attached entity (in the request body) to be stored in the server which hosts the supplied Request-URI.

If the Request-URI refers to an already existing resource – an update operation will happen, otherwise create operation should happen if Request-URI is a valid resource URI (assuming the client is allowed to determine the resource identifier).

PUT /questions/{question-id}

The POST method is used to request that the origin server accept the entity attached in the request as a new subordinate of the resource identified by the Request-URI in the Request-Line.

It essentially means that POST-request-URI should be of a collection URI.

POST /questions

PUT method is idempotent. So if we retry a request multiple times, that should be equivalent to a single request invocation.

POST is NOT idempotent. So if we retry the request N times, we will end up having N resources with N different URIs created on the server.

Use PUT when we want to modify a singular resource that is already a part of resource collection.

PUT replaces the resource in its entirety. Use PATCH if the request updates part of the resource.

Use POST when you want to add a child resource under resources collection.

Though PUT is idempotent, we should not cache its response.

Responses to this method are not cacheable unless the response includes appropriate Cache-Control or Expires header fields.

However, the 303 (See Other) response can be used to direct the user agent to retrieve a cacheable resource.

Generally, in practice, use PUT for UPDATE operations.

Always use POST for CREATE operations.

Difference between HTTP Put vs HTTP Patch?

Answer:

  • HTTP PUT: PUT is a method of modifying resources where the client sends data that updates the entire resource.
  • HTTP PATCH: Unlike PUT Request, PATCH does partial updates e.g. Fields that need to be updated by the client, only that field is updated without modifying the other field.

HTTP PUT

HTTP PATCH

PUT is a method of modifying resources where the client sends data that updates the entire resource.

PATCH is a method of modifying resources where the client sends partial data that is to be updated without modifying the entire data.

In a PUT request, the enclosed entity is considered to be a modified version of the resource stored on the origin server, and the client is requesting that the stored version be replaced.

With PATCH, however, the enclosed entity contains a set of instructions describing how a resource currently residing on the origin server should be modified to produce a new version.

HTTP PUT is said to be idempotent, So if you resend a request multiple times, that should be equivalent to a single request modification.

HTTP PATCH is said to be non-idempotent. So if you retry the request N times, you will end up having N resources with N different URIs created on the server.

It has High Bandwidth

Since Only data that needs to be modified is sent in the request body as a payload, It has Low Bandwidth.

How to unit test Web API?

Using Web API tools like Fiddler, we can perform unit testing in Web API. Fiddler is a free debugging proxy for any browser that can be used to compose and execute various HTTP requests to the Web API and check HTTP responses. 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 are some settings that need to be done, fiddler:

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

How do ASP.NET Core Secure Public APIs implement JWT Token?

There are 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 the 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.

follow these steps for JWT

  • Add Athunticcation and JWT bearer in ConfigureServices()
  • Add app,UseAthunticcation() and app.UseAuthorization in Configure()
  • At login authenticate the user and generate JWT Token
  • From now the user will send JWT Bearer Token and Athuantication middleware will automatically check and validate the JWT token.

What is CORS in Web API?

CORS (Cross-Origin Resource Sharing) is 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.