DefinitionsNetwork Programmability and Automation

What is a REST API? Fundamentals for Network Engineers

While exploring the Learning Tracks on Cisco DevNet I was able to quickly notice that the most popular and most widely used API on their new platforms is the REST API. So without losing much time I decided to study REST. I started from the perspective of a general API designer and a REST API designer. The first objective was to understand what are the benefits that have made very popular for programming and network automation platforms. The other objectives were to learn what i’m sharing next in this article.

Introduction

As the new era of network programmability, automation and SDN has arrived, it has become necessary for network engineers to learn coding. Coding allow the development of software tools. As result, network engineers can automate complex network tasks.

Communication between software tools and network platforms occurs because manufacturers have enabled better application programming interfaces or APIs. Among the network platforms the REST API has been one of the most popular. For this reason it is important to know the theoretical and practical foundations of this API.

We will start from the definition of an API and finish with the security mechanisms.

What is an API?

An API is an interface, a gateway through which an application can communicate with other applications. It offers a simple way to connect, integrate and extend software systems, no matter what programming language an application was developed in.

diagrama de flujo de un api

Distributed Software Systems are built using slightly coupled components. These components communicate using APIs.

For application developers, what is striking about an API is that it provides a reusable interface, which allows different applications to be connected in an easy way. This feature enables business software products to interface with other products, allowing new ways to quickly create businesses.

Large companies like Google, Facebook, and Amazon have APIs developed to open up opportunities for the world to create new products or expand the functionality of an existing product. We have the example of Uber who take advantage of the Google Maps APIs for their maps.

REST Architectural Style

Before defining what a REST API is, it is important to know the concept of the REST Architectural Style .

In general, an architectural style is a design of a predefined solution. Applying an architectural style allows you to build a much faster and more consistent API.

The REST architectural style defines a set of architectural restrictions and agreements, the design makes optimal use of the HTTP protocol and all its benefits.

Some of the restrictions it imposes are:

  • Use HTTP capabilities as much as possible.
  • Design Resources (Names), not Methods.
  • Use HTTP methods which have well specified semantics.
  •  Stateless communication between client and server.
  •  Use the light coupling and request independence approach.
  •  Uses HTTP State Codes for responses to requests.
  • Use MIME / Media Types.

Don’t worry, these restrictions are hard to understand at first. Understanding them requires knowing concepts that we will see later.

These constraints so dependent on the HTTP protocol make us wonder, why does REST use HTTP as a model to define its architectural style? The answer is simple, the success of HTTP-based Web sites provide living proof of the scalability and longevity of these architectures.

In summary, the most important thing is to be clear that REST is not a standard, nor is it a protocol, rather it is an architectural style made up of agreements and restrictions based on the HTTP protocol.

Advantages of REST

Each of its constraints contributes to a desirable property of the system:

  • Scalability in the system. Since REST systems are stateless and requests independent, it is possible to easily scale the system just by adding new servers.
  • Independent, stateless requests also allow fault tolerance, improving the availability and reliability of the entire system. 
  • Caching functionality can be reached for free, using existing HTTP infrastructure, such as HTTP Caches.
  • It supports the handling of multiple types of content. An API can deliver the resource in multiple alternative representations, and the client can read the responses in only one of these representations.

REST makes it easy to create a great experience for API developers and consumers too.

So what is a REST API?

Within an application, software or service, a REST API is an interface or gate, developed taking into account the agreements and restrictions defined by the HTTP protocol, to allow other applications to communicate to create, read, update or delete information.

diagrama de flujo de un api rest

Let study the REST API components in a short description that we will expand later.

Resources. A resource is an information element accessed and identified through a Uniform Resource Identifier or URI. To manipulate these resources, the client and server use a uniform HTTP interface, with which representations of these resources are exchanged.

Uniform Resource Identifier (URI). A URI is an address of a resource, that is, it indicates the location of the resource within the server that contains it. Also the URI is the identifier of the resource. URL (Uniform Resource Locator) is another way to call a URI. Both terms are interchangeable.

Example of a URI: https://api.codnova.com/routers

Representations . A resource shown in a defined format is known as a representation. In REST, a resource can be available in multiple representations, such as JSON and XML.

Uniform HTTP interface. All resources use the same uniform interface, which can be used to perform operations on the resources. A Uniform HTTP Interface defines CRUD operations to create, read, update and delete resources. CRUD Operations are defined by the HTTP POST (Create), GET (Reading), PUT (Updating) and DELETE (Deleting) methods.

Resources

A resource is an item of information that can be accessed and identified through a Uniform Resource Identifier or URI. To manipulate these resources, the client and server use a uniform HTTP interface, with which representations of these resources are exchanged.

Understanding a resource sometimes requires viewing examples, so let’s look at the following image where we have two resources.

representacion de un recurso rest y http
On the left we have a JSON representation of the “routers” resource, whose information consists of a list of routers with their name and manufacturer.
On the right we have an HTML representation of the “about-me” resource, whose information is the content of the About Me page.

As we have already seen, a resource is uniquely identified by its Uniform Resource Identifier or URI. Let’s imagine that we have a network made up of two routers, where we define each router as a resource. Each Router can be identified with the following URIs:

Router 1
URI: https://codingnetworks.blog/routers/1 

Router 2
URI: https://codingnetworks.blog/routers/2

Resource Categories

There are different categories of resources that differ in composition.

Collection Resource

A collection resource consists of a list of resources where all resources are of the same type. For example a list of routers.

{
      “Routers”: [ 
                   { 
                     “Hostname”: “R1” 
                     “Vendor”: “Cisco” 
                     “Id”: “1” 
                   }, 
                   { 
                     “Hostname”: “R2” 
                     “Vendor”: “Huawei” 
                     “Id”: “2” 
                   }
                ]
}

This collection resource can be identified with the following URI: https://codingnetworks.blog/routers

Access to a collection of resources typically contains modifiers to filter resources by a specific property or to compare resources by similar characteristics.

An example using the routers resource would be to find a resource in the collection by filtering by the resource’s hostname:

GET https://codingnetworks.blog/routers ? Hostname = R1

Instance resource

Represents a simple object. Within the collection resource «routers», a router is an instance resource.

{
    “Hostname”: “R1”
    “Vendor”: “Cisco”
    “Id”: “1”
}

This instance resource can be identified with the following URI: https://codingnetworks.blog/routers/1

Controller resource

Represents a process that runs one or multiple tasks. As we have already mentioned, an important restriction of REST is that only standard HTTP methods (GET, PUT, etc.) can be used, therefore, when you want to execute a more complex process, these types of resources are used.

Using a standard HTTP method and a series of parameters, the functionality that calls a scheduled process within the server is described. For example a simple method could trigger a process that removes all inactive routers within a list. 

This controlling resource can be identified with the following URI:
https://codingnetworks.blog/routers/inactiveRoutersRemoval

Controller resources normally when called return a state resource which allows the client to track the state of the called process. The status resource should include fields such as the current status, estimated time of the process execution, among others.

An example of a state resource can be:
URI: https://codingnetworks.blog/routers/duplicateRemoval/212010

By consulting the server about the status of this resource with the GET method, you can obtain information on the progress of the process and the estimated time for completion.

Example:
GET https://domain.com/routers/duplicateRemoval/212010

Response: 200 OK
{
  “Progress: “20%”,
  “Estimated_time_to_completion” : “ 5 min 4 sec”
}

Uniform Resource Identifier or URI

A URI is defined by RFC 3986 as an identifier consisting of a sequence of characters or components that follow a defined syntax. Next we are going to decompose a URI to understand the functions of each of its components.

Ejemplo: https://codingnetworks.blog:80/routers/1?hostname=R1&vendor=Cisco

  • “Https”. Specifies the protocol to use to access the resource.
  • “Codnova.com”. Identifies the server or host where the resource is located.
  • “80”. Specifies the port number on which the server or host is waiting for requests to come in.
  • “/ Routers / 1”. Indicates the path of the resource within the server.
  • “? Hostname = R1 & vendor = Cisco”. They are a set of parameters that allow you to search or filter a resource.
  • Special characters used to separate the components:
    • “: //”. Used to separate the protocol (http) from the host (codnova.com).
    • «:». Used to separate the host (codnova.com) from the logical port number (80).
    • «/». Used to hierarchically separate resources and their components.
    • “,” Or “;”. Used to separate non-hierarchical resources.
    • “-” or “_”. Used to structure resources with long names.
    • “?”. Used to separate the resource path from the search or filter parameters.
    • “&”. If there are multiple search or filtering parameters, it is used to separate them from each other.

Representations

A representation is a serialization of a resource. A resource is merely raw data. To transfer a resource between the REST API and the client, it is first necessary to serialize it, that is, encode it in a format agreed between both parties. Therefore the representations are nothing more than serialized resources that are transmitted between client and the REST API.

To serialize a resource into a representation and to deserialize the representation back into a resource, you must follow a set of serialization rules. In HTTP, MIME-Types can be used as Serialization Rules. JSON and XML are serialization rules commonly used to create representations.

When a representation is sent via HTTP, we can find it in the body of the request and response of the HTTP package. The serialization rules used to create the representation are specified in the HTTP header. The Content-Type field of the HTTP header is the one used to specify the serialization rules. For a JSON representation, the value would be “application / json”.

ejemplo de la informacion de una respuesta REST

Serialization rules are specified according to an standard called Multipurpose Internet Mail Extensions (MIME), defined in IEFT RFC 2045. The serialization rules, specified according to the MIME standard are called MIME-Type (Content-Type). An example of this rule according to the standard is the one we already mentioned for JSON, called «application / json».

Parameters

A REST API typically does not return static data, instead it returns dynamic data that depends on inputs provided by the client or consumer. An API can receive inputs via the HTTP Body and via HTTP parameters.

We will see below the cases in which inputs to an API are provided via parameters.

Create and Update a Resource

When creating a new resource, the fields of this new resource need to be filled with initial values. These values ​​are sent as inputs to the API.

If the resource is created with the POST method, the initial values ​​for the resource fields are transferred as Parameters Forms .

The Form Parameters are Key-Value pairs, where the key is the name of the parameter and Value is the value of the parameter. Let’s see the following example in which we have the keys (hostname and vendor) and the values ​​(R1 and Cisco).

POST  https://codingnetworks.blog/routers?hostname=R1&vendor=cisco

If a resource is created or updated with the PUT method, the data input is sent as a representation via the HTTP Body.

{
    “Hostname”: “R1”
    “Vendor”: “Cisco”
    “Id”: “1”
}
Resource Recovery: Filtering and Sorting

We already know that a collection resource is a set of resources of the same type. There are occasions where a customer is only interested in a small group in the collection. The REST API offers functionality to filter a collection, search a collection, and sort a collection.

Filters are commonly configured through filtering criteria. Ordering requires specifying the sorting criteria. This can be expressed through Query Parameters .

The query parameters are key-value pairs that are attached to the URI of the resource. Multiple query parameters can be concatenated, forming a list.

An Ordinate query would be:

GET  https://codingnetworks.blog/routers?sort=hostname&sortOder=desc

Recovering a Resource: Locators

Locators provide information to identify a resource, such as the URI. In REST, locators are normally presented as Route Parameters . The Route Parameters in a URI represent a resource.

The Route Parameters are part of the URI and therefore become part of the Resource Identifier.

Recovery of a Resource: Projections

There are situations where clients do not want all the information contained in a resource. The REST API offers functionality to limit the fields of the resource you want to receive.

Projections allow you to select fields and only include these in the response. These provide a partial view of the resource. Projections can be applied to Collection Resources and Instance Resources. Some examples would be:

Projection in
GET  Collection Resource https://codingnetworks.blog/routers?fields=hostname

Projection in
GET  Instance Resource https://codingnetworks.blog/routers/1/hostname
or
GET  https://codingnetworks.blog/routers/1?fields=hostname

Multiple
GET  Fields https://codingnetworks.blog/routers/1?fields=hostname, vendor

Múltiples Campos
GET  https://codingnetworks.blog/routers/1?fields=hostname, vendor

Header Parameters

parametros de una solicitud y respuesta REST
Generic Header Parameters

Generic header parameters are those that can be used in both the API Request message and the API Response message. We are going to define some of the most common:

  • Content-Type: Indicates what is the syntax and semantics of the HTTP Body. It is also known as MIME-Type.
  • Content-Length: Indicates the length of the content in Bytes. It allows the receiver to check if she has received the complete content.
  • Content-Language: Specifies the language of the Representation, using a two letter code according to RFC 5646.
  • Content-Location: Indicates the address in which the content of the HTTP Body can be retrieved with a GET. This indicates that the HTTP body contains a copy of the resource, whose address is given in the Content-Location Header. 
  • Content-Encoding: Indicates the compression method used. The allowed values ​​are: gzip, compress or deflate.
  • Content-MD5: Contains a Hash of the content to verify its integrity.
  • Date: It is a label that contains the time when the request was sent.
  • Host: Indicates which is the Host or destination to be contacted.
Request Header Parameters

In addition to the Generic Header Parameters, the most common Request Parameters that are sent in a Request to the API are:

  • User-Agent: Client Identifier.
  • Referer: Specifies the URL form where the URL of the current request was obtained.
  • Expect: Indicates the Status Code expected by the client.
  • From: Contains an email address of the User sending the request.
  • Max-Forward: Maximum number of jumps in a TRACE Request.
  • Accept: Specifies a list of Media Types, which the Agent User can accept in response.
  • Accept-Charset: Specifies a set of characters, which the Agent User can accept in response.
  • Accept-Enconding: Specifies an encoding, which the Agent User can accept in response.
  • Accept-Language: Specifies the languages ​​that the Agent User can accept in response.
  • MIME-Version: Specifies the version of the MIME protocol that is used.
Response Header Parameters

The following parameters are normally used in the response that is sent from the API to clients:

  • Status: Contains the HTTP Status Code, indicating Success or failure reason.
  • Retry-After: Indicates how long the Agent User must wait before forwarding a request. Typically they are used in combination with a 5XX Status Code.
  • Location: Indicates the URL of the resource, which is relevant to this response.
  • Allow: List all the methods that can be used with a respective resource.
  • Server: Like the User-Agent header, it allows identifying the Software that was used to produce the request. The Server header identifies the software and version that was used to reproduce the response.
  • Vary: Specifies which Request headers influence the representation’s choice during the Negotiation.
  • Age: Specifies the amount of time that has passed since the Response was generated.
  • Cache-Control. It is selected by the API and is the main control for Caching. It allows the configuration of multiple policies:
    • The Max-age
    • No-cache directive
    • Public directive
    • Private directive
    • Must-revalidate directive.
  • Date: Specifies when the e-response was sent and helps clients compute the Refresh Time.

State Codes

When a method is executed on an HTTP resource, this as a response returns at least one status code, which basically indicates the success or failure of the operation. It is with this code that the client determines the next steps to follow.

For each of these success or error cases, the HTTP Status Code is defined as a numeric code and a short description.

The numerical status code is made up of 3 digits. The first digit groups the State Codes into 5 groups:

Informational Status Codes (1xx): Non-Critical Information.

State CodeState MessageMeaning
100 Continue Indicates that the initial part of the Request was received.

Status Codes of Success (2xx): The request was successfully processed.

State CodeState MessageMeaning
200OKThe Request was successfully processed
201CreatedIndicates that one or more resources were created
202AcceptedIndicates that the request has been accepted for processing but the process has not finished.
203Non-Authoritative InformationIt indicates that the request was successful, but that the Payload has been modified by a Proxy.
204 No Content Indicates that the request was successful but that the HTTP Body does not contain a response.

Redirection Status Codes (3xx): The client has to make another request based on the parameters of the header received in the response.

State CodeState MessageMeaning
300 Multiple Choices Multiple resources coincided with the consultation made.
301 Moved Permanently Redirects the query to the specified address.

Client Error Status Codes (4xx): An error has occurred. The customer is responsible for the problem.

State CodeState MessageMeaning
400 Bad Request Incorrect Syntax in the Request.
401 UnauthorizedFailed request, unauthenticated user.
402Insufficients FundsInsufficient funds.
For Monetized APIs.
403ForbiddenFailed request, user does not have authorization to access the resource.
404Not FoundThe resource was not found.
405Method not Allowed HTTP method specified in the request is not allowed.
406Not Acceptable The API cannot produce a response with a MEdia-Type that the client can accept.
408 Request Timeout Indicates that the server did not receive a complete request.
409 Conflict Indicates that there is a conflict with the current status of the resource.

Server Error Status Codes (5xx): An error has occurred. The Server or API is responsible for the problem.

State CodeState MessageMeaning
500 Internal Server Error An unexpected condition occurred in the API and an exception was thrown.
501Not Implemented The functionality requested by the client is not yet implemented.
502Bad Gateway The server acting as Gateway or Proxy obtained an invalid response from the Backend
503Service UnavailableThe server cannot process the request or the connection was rejected.

Security in a REST API

Exposing software systems via an API opens up a large number of security-level challenges. As expected, the REST API comes with mechanisms to deal with Security issues concerning:

  • Authentication
  • Authorization
  • Delegation
  • Identity
  • Attacks

Security mechanisms

API keys

An API key is a unique identifier, which is required for every request made to the API. The unique key allows to identify the client and authorize them to access the Resources that they have permission to access. This means that an API Key can be used for both Authentication and Authorization. Therefore the must be kept confidential.

The API interaction platform and the API runtime platform generate and manage the API key. The API interaction platform generally runs as a self-service portal.

proceso interaccion rest api con seguridad llave api

When calling the API, the client provides the API key as a parameter in the request. The API Runtime platform verifies the API key provided in the API key database. With this process the API consumer is authenticated and the request is authorized verifying that the API consulted is in the set of APIs that this key is allowed to access.

Generally speaking, API keys provide a lightweight mechanism for authentication and authorization of API clients.

HTTP Basic

proceso interaccion rest api con seguridad http basic

HTTP Basic is a simple mechanism for authentication and authorization of an API request. It is compatible with many libraries and HTTP servers. The API client first requests the API credentials on the API interaction platform, and uses them when making an API call, providing username and password in the HTTP Authorization header.

HTTP Digest

The summary, HTTP Digest follows the same principles as Basic HTTP, but it is a little more secure. It uses a challenge-response mechanism, which consists of the following steps:

OAuth

rest api, proceso oauth autenticación

OAuth is a standard for delegating authorizations, registered in IETF RFC 6749. With OAuth, an end user gets an API access token and can provide it to any third party application or simple application thus delegating their access rights to this application. The token represents access rights for a subset of data, for a short period of time.

Some REST APIs

Below I have provided a few free REST APIs that use different security mechanisms.

No Security / Open

Oauth

API Key

Conclusion

I hope you were able to learn a little more about REST APIs. If you have any questions or doubt, please comment below. Any word that helps improve and enrich this content is welcome.

By Michael Alvarez

One Comment

Comments are closed.