Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Web API Basic Concepts and Example

Do you know what a Web Api is and how it is built? The purpose of this post is that you get to know all the concepts needed to fully understand how it works. Also, at the end of this post, I will show you how to create a Web API project and how easy it is to configure it.

What is an ASP.NET WEB-API and what is it useful for?

  • ASP.NET Web API is a framework that makes it easy to build HTTP services that reach a broad range of clients, including browsers and mobile devices.
  • It is built in asp.net
  • It was released with MVC4, although it is not necessary to use MVC4, it can be used in web forms for example.

What does HTTP mean?

HTTP stands for HyperText Transfer Protocol. It is an application protocol for distributed, collaborative, hypermedia information systems that transfer data over the web.

HTTP is based on Request-response operations. A client establishes a connection with a server and sends a message with the request data. The server responds with a similar message that contains the state of the operation and a result.

What is an API?

API stands for Application Programming Interface and it is a set of functions and procedures that allow the creation of applications that access the features or data of an operating system, application, or other services.

What is REST?

REST stands for Representational State Transfer. It is a type of software architecture for distributed systems such as www, where, virtually in all cases, the HTTP protocol is used.

Rest Constraints

The rest architectural pattern specifies a set of constraints that the system should adhere to. These constraints are:

  • Client-Server: Client sends a request and the server sends a response. This separation of concerns supports the independent evolution of the client's logic and server-side logic.
  • Stateless: the communication between the client and the server must be stateless between requests. This means we should not store on the server anything related to the client. The request from the client should contain all the necessary information for the server to process that request. This ensures that each request can be treated independently by the server.
  • Cacheable: the data provided by the server that doesn’t change that often can be cached. We should let the client know for how long this data is good for so the client does not have to come back to the server for the same data over and over again. Caching avoids unnecessary processing and increases the performance of the system.
  • Uniform interface: this constraint assures that
    1. Individual resources are identified in requests.
    2. When a client holds a representation of a resource, it has enough information to modify or delete the resource
    3. Self-descriptive message: each message has enough information to describe how to process the message. For example which parser to invoke.
    4. Hypermedia as the engine of the application state: having accessed an initial URI for the rest application, a Rest client should then be able to use server-provided links dynamically to discover all the available actions and resources it needs.
  • Layered System: allows to use layered system architecture, for example, you can deploy the APIs on one server, and store data on another server.
  • Code on demand (optional): it allows you to return executable code

Each HTTP request has:

  • URI: stands for Uniform Resource Identifier. It is a string of characters designed for unambiguous identification of the resource and extensibility via the URI scheme.
  • Http Verb: It could be POST, GET, PUT, DELETE. Each one is used for 1 of the crud operations as you can see in the grid above.
  • Http Header allows the client and the server to pass additional information with the request or the response. An HTTP header consists of its case-insensitive name followed by a colon ‘:’, then by its value.
  • Http Body: contains the data to send to the server

Each HTTP response contains :

  • Response status code: provide the client, the status of the request. The most common once are 200 for ok and 404 for a resource not found. If you want to see a complete list of status codes and what they mean click here. But as a reference, you should know that Status codes are grouped into 5 classes:
    1. Informational responses (100–199)
    2. Successful responses (200–299)
    3. Redirects (300–399)
    4. Client errors (400–499)
    5. Server errors (500–599)
  • Response body: contains the data sent as a response from the server.

How does WEB-API work?

In ASP.NET Web API, a controller is a class that handles HTTP requests. The public methods of the controller are called action methods or simply actions. When the Web API framework receives an HTTP request, using the routing it detects in which controller is the action that needs to be invoked.

Routing

It is how the webAPI matches a URI to an action.

  • Convention-based routing: To determine which action to invoke, the framework uses a routing table that is created based on the route templates defined by the user. When the framework receives a request, it matches the URI against the templates. Although this type of routing has some advantages, sometimes it makes hard to support certain URI patterns. So it is commonly combined with the Attribute routing
  • Attribute routing: it allows you to define a route by adding an attribute to the controller action.

Let’s create our first webApi project

Step 1: Create a C# MVC project

  • Go to visual studio and click file / new project.
  • select asp.net web application and click next
  • Give a name to the project and click create
  • Select web-API template and click create

Step 2: Create an object model

For this example, we are going to create an API of airports, so under the Models folder, create the airport.cs

Step 3: Implement a method to get all the airports.

Create an AirportController.cs inside Controllers directory. This class should inherit from ApiController.

Since the post is about webApi and not how to access to the database to get information, let’s create a list of airports “airports” inside the class as our data-source, and implement a Get method that returns all the airports.

Step 4: download a rest client, I use tabbed postman-Rest client chrome extension, if you want to download click here

Step 5: let’s try if we can get all the airports.

Build the application and make a get request using the rest client to https://localhost:44353/api/Airport, to get all the airports. Remember to replace 44353 for the correct port number.

Before continuing, let’s understand what is going on behind the since.

The rest-client is making a request to the server

Request:

  • URI: https://localhost:44353/api/Airport
  • Body: We didn’t specify a request body because we didn’t need to send anything to the server
  • HTTP verb: Get
  • Header: Content-Type: application/JSON

Response:

  • status code 200
  • Response body: a list with airports

But how does the server matches the request with the result?

As I mentioned before, this is done by the routing. When the application starts, it goes to Global.asax.cs and execute Application_start event handler method, there is where we need to configure the web-API to work, we do that by calling the register method in the WebApiConfig.cs.

The webApiConfig is located under App_Start directory. There is where routing is defined. This is convention-based routing.

The default route includes “api” to avoid conflicts with MVC routes. the {controller} is replaced by the controller Name in our case Airport and the 3rd parameter is the Id and it is optional.

Step 6: implement get by Id method

In the AirportController , create a method named get that receives an id as a parameter and returns the correct airport.

Step 7: implement a Post method to save a new value in the list of airports.

Now if we make a post request we can add a new airport to our list.

Step 8: Implement a put method, that receives an airport to modify. And a delete method to remove an airport from the list.

Step 9: let’s see how to enable attribute-routing.

In the WebApiConfig.cs call the method MapHttpAttributeRoutes of the config object.

Now let’s define a new method to get the names of the cities where the airports are.

Attribute-routing and convention-based routing can be combined.

As you can see, all the methods that we defined start with one of the HTTP verbs, if you want to define a method that doesn’t start with the HTTP verb you need to decorate the method with the correct attribute [HttpDelete],[HttpGet],[HttpPost], etc.

Let’s say for example you want to name Remove the method that deletes an airport, in that case, you should write it like this.

I hope you found this post useful.

Thank you for reading!

Source:

  • https://en.wikipedia.org/wiki/Uniform_Resource_Identifier
  • https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers
  • https://app.pluralsight.com/library/courses/aspnetwebapi-odata/table-of-contents
  • https://en.wikipedia.org/wiki/Representational_state_transfer
  • https://developer.mozilla.org/en-US/docs/Web/HTTP/Status
  • https://docs.microsoft.com/en-us/aspnet/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2

Would you like to know more? Do you need our help? Contact Us!
www.quadiontech.com


Web API Basic Concepts and Example was originally published in Quadion Technologies on Medium, where people are continuing the conversation by highlighting and responding to this story.



This post first appeared on Quadion Technologies, please read the originial post: here

Share the post

Web API Basic Concepts and Example

×

Subscribe to Quadion Technologies

Get updates delivered right to your inbox!

Thank you for your subscription

×