Let’s understand what an API is

Let’s understand what an API is

The basic principles for building REST APIs are based on knowing mostly HTTP, something that is not optional for a web developer.

What is REST?

REST, REpresentational State Transfer, is a type of web development architecture that is fully supported by the HTTP standard.

REST allows us to create services and applications that can be used by any device or client that understands HTTP, so it is incredibly simpler and more conventional than other alternatives that have been used in the last ten years as SOAP and XML-RPC.

REST was defined in 2000 by Roy Fielding, co-author also of the HTTP specification. We could consider REST as a framework to build web applications respecting HTTP.

Therefore REST is the most natural and standard type of architecture to create APIs for Internet-oriented services.
There are three levels of quality when REST is applied in the development of a web application and, more specifically, an API that is collected in a model called Richardson’s Maturity Model in honor of the type that established it, Leonard Richardson, father of architecture oriented to resources.

These levels are:

  1. Correct use of URIs.
  2. The correct use of HTTP.
  3. Implement Hypermedia.

In addition to these three rules, you should never save state on the server, all the information that is required to show the information that is requested must be in the query by the client.

By not saving state, REST gives us a lot of play, since we can scale better without having to worry about issues such as storage of session variables and even, we can play with different technologies to serve certain parts or resources of the same API.

Level 1: Correct use of URIs

When we develop a web or a web application, the URLs allow us to access each of the pages, sections or documents of the website.

Each page, information in a section, file, when we talk about REST, we name them as resources.

The resource is, therefore, the information that we want to access, modify or eliminate, regardless of its format.

The URL, Uniform Resource Locator, is a type of URI, Uniform Resource Identifier, which, in addition to allowing to identify the resource in a unique way, allows us to locate it to access or share its location.

A URL is structured as follows:

{protocol}://{domain or hostname}[:port (optional)]/{resource route}?{filtering query}

There are several basic rules to name the URI of a resource:

  • URI names should not imply an action, therefore, you should avoid using verbs in them.
  • They must be unique, we must not have more than one URI to identify the same resource.
  • They must be independent of format.
  • They must maintain a logical hierarchy.
  • Filtering the information of a resource is not done in the URI.

URIs should not involve actions and should be unique.

For example, the URI /invoices/234/edit would be incorrect since we have the verb edit in it.

For the invoice resource with the identifier 234, the following URI would be the correct one, regardless of whether we are going to edit it, delete it, consult it or read only one of its concepts: /invoices/234.

URIs must be independent of format

For example, the URI /invoices/234.pdf would not be a correct URI, since we are indicating the pdf extension in it.

For the invoice resource with the identifier 234, the following URI would be the correct one, regardless of whether we are going to consult it in pdf format, epub, txt, xml or json: /invoices/234.

URIs must maintain a logical hierarchy

For example, the URI /invoices/234/client/007 would not be a correct URI, since it does not follow a logical hierarchy.

For the invoice resource with the identifier 234 of the client 007, the following URI would be the correct one: /clients/007/invoices/234.

Filtering and other operations

To filter, sort, search or search information in a resource, we must make a query about the URI, using HTTP parameters instead of including them in it.

For example, the URI /invoices/order/desc/date-from/2007/page/2 would be incorrect, since the invoice listing resource would be the same, but we would use a different URI to filter, classify or locate it.

The correct URI in this case would be:

/invoices?date-from=2007&order=DESC&page=2

Level 2: HTTP

Knowing well HTTP is not optional for a web developer who cares about their work. Although the RFC is easy to read, if you are interested in learning the basics of this protocol well, the orientation of O’Reilly is strongly recommended.

To develop the REST APIs, the key aspects that must be mastered and clarified are:

  • HTTP methods.
  • Status codes.
  • Acceptance of content types.

Methods

As we have seen in the previous level, when creating URI we should not put verbs that imply action, even if we want to manipulate the resource.

To manipulate resources, HTTP gives us the following methods with which we must operate:

  • GET: To consult and read resources.
  • POST: To create resources.
  • PUT: To edit resources.
  • DELETE: To eliminate resources.
  • PATCH: To edit specific parts of a resource.

For example, for an invoice resource:

  • GET /invoices → Allows us to access the list of invoices.
  • POST /invoices → Allows us to create a new invoice.
  • GET /invoice/123 → Allows us to access the detail of an invoice.
  • *PUT /invoices/123 *→ Allows us to edit the invoice, replacing the entire previous information with the new one.
  • DELETE /invoices/123 → Allows us to delete the invoice.
  • PATCH /invoices/123 → It allows us to modify certain information of the invoice, such as the number or date of the invoice.

Perhaps due to ignorance or the support of certain browsers, web developers have used, during the last few years, only the GET and POST methods to perform all these actions. If we work with REST, this would be a basic error and can give us problems even when it comes to assigning a name to our resources, which forces us to put verbs in the URLs.

Status codes

One of the most frequent errors when creating an API is to reinvent the wheel when creating our own tools instead of using those that have already been created, thought and tested. The most reinvented wheel in the development of the APIs are the error codes and the status codes.

When we perform an operation, it is vital to know if this operation has been carried out successfully or, in the opposite case, why it has failed.

A common mistake would be for example:

Request
=======
PUT /invoices/123

Response
========
Status Code 200
Content:
{
  success: false,
  code:    734,
  error:   "Insufficient data"
}

In this example, a status code of 200 is returned, which means that the request was successful, however, we are returning an error in the body of the response and not in the requested resource in the URL.

This is a common error that has several drawbacks:

  • It is not REST nor is it standard.
  • The client that accesses this API must know the special operation and how to deal with its errors, so it requires an important additional effort to work with us.
  • We have to worry about keeping our own codes or error messages, with all that implies.

HTTP has a very wide range that covers all the possible indications that we are going to have to add in our answers when the operations have gone well or badly. It is imperative to know them and know when to use them, regardless of what you develop following REST.

The previous example would be correct in the following way:

Request
=======
PUT /invoices/123

Response
========
Status Code 400
Content:
{
  message: "A customer id must be specified for the invoice"
}

Types and formats of content

When we talked about URL, we also saw that it was not correct to indicate the type of format of a resource that we want to access or manipulate.

HTTP allows us to specify in what format we want to receive the resource, being able to indicate several in order of preference, for this we use the Accept header.

Our API will return the resource in the first available format and, if the resource can not be displayed in any of the formats indicated by the client using the Accept header, it will return the HTTP status code 406.

In the answer, the Content-Type header will be returned, so that the client knows what format is returned, for example:

Request
=======
GET /invoices/123
Accept: application/epub+zip, application/pdf, application/json

Response
========
Status Code 200
Content-Type: application/pdf

In this case, the client requests the invoice in compressed epub with ZIP and if not, in pdf or json in order of preference. The server finally returns the invoice in pdf.

Level 3: Hypermedia

Despite what may lead us to think about the term retrofuturist hypermedia, the concept and purpose it tries to describe is quite simple: connect through the links of client applications with APIs, allowing these customers worry about knowing in advance how to access resources.

With Hypermedia we basically add extra information to the resource about its connection to other resources related to it.

Here an example:

<order>
  <id>666</id>
  <status>Processed</status>
  <links>
    <link rel="invoice">
        http://example.com/api/order/666/invoice
    </link>
  </links>
</order>

In this example we see how to indicate in an xml that represents an order, the link to the resource of the invoice related to it.

However, we need the client that accesses our API to understand that this information is not specific to the resource, but is added information that can be used to link the order with the invoice.

To do this, we must use the Accept and Content Type headers, so that both the client and the API know they are talking about hypermedia.

For example:

Request
=======
GET /order/666
Accept: application/our_api+xml, text/xml
Response
========
Status Code: 200
Content-Type: application/our_api+xml
Content:
<order>
  <id>666</id>
  <status>Processed</status>
  <links>
    <link rel="invoice">
         http://example.com/api/order/666/invoice
    </link>
  </links>
</order>

As we can see, the client requests the application/our_api+xml format preferably in text/xml format. In this way, it tells the web service, that it understands its hypermedia format and can take advantage of it.

The web service therefore, as it implements hypermedia, returns the resource information and hypermedia information that the client can use.

Hypermedia is useful for example so that the client does not have to know the URLs of the resources, avoiding having to do maintenance on each of them if in the future said URLs change (which should not happen). It is also useful for automating processes between APIs without human interaction.

Conclusion

As we have seen, the basic principles for building REST APIs are based on knowing mostly HTTP, something that is not optional for a web developer.

Thanks for reading ❤

If you liked this post, share it with all of your programming buddies!

What the difference between REST API and RESTful API?

What the difference between REST API and RESTful API?

Representational state transfer (REST) is a style of software architecture. As described in a dissertation by Roy Fielding, REST is an "architectural style" that basically exploits the existing technology and protocols of the Web. RESTful is typically used to refer to web services implementing such an architecture.

The short answer is that REST stands for Representational State Transfer. It’s an architectural pattern for creating web services. A RESTful service is one that implements that pattern.

The long answer starts with “sort of” and “it depends” and continues with more complete definitions.

Defining REST

Let’s start by defining what REST is and is not. For some, REST means a server that exchanges JSON documents with a client over HTTP. Not only is that not a complete definition, but it’s also not always true. The REST specification doesn’t require HTTP or JSON. (The spec doesn’t mention JSON or XML at all.)

The Origins of REST

Roy Fielding introduced the REST architectural pattern in a dissertation he wrote in 2000. The paper defines a means for clients and servers to exchange application data. A key feature is that the client doesn’t need to know anything about the application in advance. The link is to chapter five of his paper. While the entire dissertation describes the hows and whys of REST, that chapter defines the architectural pattern.

Fielding doesn’t mandate specific requirements. Instead, he defines REST regarding constraints and architectural elements.

REST’s Architectural Constraints

Here is a summary of the constraints.

  • Client-server – REST applications have a server that manages application data and state. The server communicates with a client that handles the user interactions. A clear separation of concerns divides the two components. This means you can update and improve them in independent tracks.
  • Stateless – servers don’t maintain any client state. Clients manage their application state. Their requests to servers contain all the information required to process them.
  • Cacheable – servers must mark their responses as cacheable or not. So, infrastructures and clients can cache them when possible to improve performance. They can dispose of non-cacheable Information, so no client uses stale data.
  • Uniform interface – this constraint is REST’s most well known feature or rule, depending on who you ask. Fielding says “The central feature that distinguishes the REST architectural style from other network-based styles is its emphasis on a uniform interface between components.” REST services provide data as resources, with a consistent namespace. We’ll cover this in detail below.
  • Layered system – components in the system cannot “see” beyond their layer. So, you can easily add load-balancers and proxies to improve security or performance.

A RESTful service is more than a web server that exchanges JSON, or any other, documents. These constraints work together to create a very specific type of application.

Applying the Constraints

First, the client-server, layered systems and stateless constraints combine to form an application with solid boundaries and clear separations between concerns. Data moves from the server to the client upon request. The client displays or manipulates it. If the state changes, the client sends it back to the server for storage. Fielding specifically contrasts REST with architectures that use distributed objects to hide data from other components. In REST, the client and server share knowledge about data and state. The architecture doesn’t conceal data, it only hides implementations.

The cacheable and uniform state constraints go one step further. Application data is available to clients in a clear and consistent interface and cached when possible.

So, that’s the technical definition of REST. What does it look like in the real world?

RPC Over HTTP vs. RESTful

Often when someone says that a service “isn’t REST,” they’re looking at the URIs or how the service uses HTTP verbs. They’re referring to REST’s presentation of data as a uniform set of resources.

This distinction is sometimes framed as a difference between remote procedures calls (RPC) and REST. Imagine a web service for listing, adding, and removing, items from an e-commerce inventory.

In one version, there’s a single URL that we query with HTTP GETs or POSTs.  You interact with the service by POSTing a document, setting the contents to reflect what you want to do.

Add new items with a POST with a NewItem:

POST /inventory HTTP/1.1
 
{
    "NewItem": {
          "name": "new item",
          "price": "9.99",
          "id": "1001"
      }
}    

Query for items with a POST and an ItemRequest:

POST /inventory HTTP/1.1
 
{
    "ItemRequest": {
          "id": "1001"
      }
}

Some implementations accept a request for a new item with a get, too.

POST /inventory?id=1001 HTTP/1.1

We also change or delete items with a POST and an ItemDelete or ItemUpdate.

POST /inventory HTTP/1.1
 
{
    "ItemDelete": {
          "id": "1001"
      }
}

This isn’t REST. We’re not exchanging the state of resources. We’re calling a function with arguments that happen to be in a JSON document or URL arguments.

A RESTful service has a URI for each item in the inventory.

So, adding a new item would look like the example above.

POST /item HTTP/1.1
 
{
    "Item": {
          "name": "new item",
          "price": "9.99",
          "id": "1001"
      }
}    

But the similarities end there. Retrieving an item is always a GET:

GET /item/1001 HTTP/1.1   

Deleting is a DELETE:

DELETE /item/1001 HTTP/1.1  

Modifying an item is a PUT:

POST /inventory HTTP/1.1
 
{
    "Item": {
          "name": "new item",
          "price": "7.99",
          "id": "1001"
      }
}    

The difference is important. In REST, operations that use distinct HTTP actions. These verbs correspond directly to the activity on the data. GET, POST, PUT, DELETE and PATCH all have specific contracts. Most well-designed REST APIs also return specific HTTP codes, depending on the result of the request.

The critical point is that the URIs operate on the data, not on remote methods.

But there’s another reason why the resource model is essential.

REST vs RESTful and the Richardson Maturity Model

When you model your URIs after resources and use HTTP verbs you make your API predictable. Once developers know how you defined your resources, they can almost predict what the API looks like. Here again, the emphasis is on understanding the data, not the operations.

But even if you can’t make the API entirely predictable, you can document any REST service with hypertext. So, each item returned in the inventory app would contain links for deleting, modifying, or setting the inventory level of the resource. Fielding says that before a service is RESTful, it must provide hypertext media as part of the API.

Many sites don’t meet this requirement but are still called REST. Fact is, many sites break the rules in one way or another. So many that Leonard Richardson created a model breaks down REST into levels of compliance

We’ve already covered the source levels:

  • 0 – exporting an API over HTTP with methods called with arguments
  • 1 – Exporting resources instead of methods
  • 2 – Proper use of HTTP verbs
  • 3 – Exporting hypertext with objects that make all or part of the API discoverable.

Richardson’s model is his own, and it doesn’t map directly into Fielding’s spec. Since Fielding requires level three, he would say that most apps aren’t REST anyway.

The point is many services that we colloquially refer to as REST, technically aren’t.

REST vs RESTful: Does It Matter?

So, does the REST vs. RESTful comparison matter? Probably not. How well your architecture complies with an arbitrary standard isn’t as important with how well it suits your needs and can grow with your business.

The REST architectural pattern has many advantages. Fielding designed it for the web and, 18 years later, most of the constraints he had in mind are still with us. In 2000 we didn’t have Android or the iPhone. IE5 had 50% of the browser market share. It’s biggest rival was Firefox. But Fielding recognized what online applications needed and how web clients would evolve from HTML display engines into complete applications. The tools we use today have grown to suit REST, not the other way around.

Thank you for reading. Hope this tutorial will help you!

What is REST API? | Restful Web Service

What is REST API? | Restful Web Service

In this post "Restful Web Service", you'll learn: What is Web services, what is API, What is REST API, How REST works and Implementation of REST API

What is REST API? | Restful Web Service

A REST API defines a set of functions to process requests and responses via HTTP protocol.

REST is used in mobile application as well as in web applications.


What the difference between REST API and RESTful API?

What the difference between REST API and RESTful API?

Representational state transfer (REST) is a style of software architecture. As described in a dissertation by Roy Fielding, REST is an "architectural style" that basically exploits the existing technology and protocols of the Web. RESTful is typically used to refer to web services implementing such an architecture.

The short answer is that REST stands for Representational State Transfer. It’s an architectural pattern for creating web services. A RESTful service is one that implements that pattern.

The long answer starts with “sort of” and “it depends” and continues with more complete definitions.

Defining REST

Let’s start by defining what REST is and is not. For some, REST means a server that exchanges JSON documents with a client over HTTP. Not only is that not a complete definition, but it’s also not always true. The REST specification doesn’t require HTTP or JSON. (The spec doesn’t mention JSON or XML at all.)

The Origins of REST

Roy Fielding introduced the REST architectural pattern in a dissertation he wrote in 2000. The paper defines a means for clients and servers to exchange application data. A key feature is that the client doesn’t need to know anything about the application in advance. The link is to chapter five of his paper. While the entire dissertation describes the hows and whys of REST, that chapter defines the architectural pattern.

Fielding doesn’t mandate specific requirements. Instead, he defines REST regarding constraints and architectural elements.

REST’s Architectural Constraints

Here is a summary of the constraints.

  • Client-server – REST applications have a server that manages application data and state. The server communicates with a client that handles the user interactions. A clear separation of concerns divides the two components. This means you can update and improve them in independent tracks.
  • Stateless – servers don’t maintain any client state. Clients manage their application state. Their requests to servers contain all the information required to process them.
  • Cacheable – servers must mark their responses as cacheable or not. So, infrastructures and clients can cache them when possible to improve performance. They can dispose of non-cacheable Information, so no client uses stale data.
  • Uniform interface – this constraint is REST’s most well known feature or rule, depending on who you ask. Fielding says “The central feature that distinguishes the REST architectural style from other network-based styles is its emphasis on a uniform interface between components.” REST services provide data as resources, with a consistent namespace. We’ll cover this in detail below.
  • Layered system – components in the system cannot “see” beyond their layer. So, you can easily add load-balancers and proxies to improve security or performance.

A RESTful service is more than a web server that exchanges JSON, or any other, documents. These constraints work together to create a very specific type of application.

Applying the Constraints

First, the client-server, layered systems and stateless constraints combine to form an application with solid boundaries and clear separations between concerns. Data moves from the server to the client upon request. The client displays or manipulates it. If the state changes, the client sends it back to the server for storage. Fielding specifically contrasts REST with architectures that use distributed objects to hide data from other components. In REST, the client and server share knowledge about data and state. The architecture doesn’t conceal data, it only hides implementations.

The cacheable and uniform state constraints go one step further. Application data is available to clients in a clear and consistent interface and cached when possible.

So, that’s the technical definition of REST. What does it look like in the real world?

RPC Over HTTP vs. RESTful

Often when someone says that a service “isn’t REST,” they’re looking at the URIs or how the service uses HTTP verbs. They’re referring to REST’s presentation of data as a uniform set of resources.

This distinction is sometimes framed as a difference between remote procedures calls (RPC) and REST. Imagine a web service for listing, adding, and removing, items from an e-commerce inventory.

In one version, there’s a single URL that we query with HTTP GETs or POSTs.  You interact with the service by POSTing a document, setting the contents to reflect what you want to do.

Add new items with a POST with a NewItem:

POST /inventory HTTP/1.1
 
{
    "NewItem": {
          "name": "new item",
          "price": "9.99",
          "id": "1001"
      }
}    

Query for items with a POST and an ItemRequest:

POST /inventory HTTP/1.1
 
{
    "ItemRequest": {
          "id": "1001"
      }
}

Some implementations accept a request for a new item with a get, too.

POST /inventory?id=1001 HTTP/1.1

We also change or delete items with a POST and an ItemDelete or ItemUpdate.

POST /inventory HTTP/1.1
 
{
    "ItemDelete": {
          "id": "1001"
      }
}

This isn’t REST. We’re not exchanging the state of resources. We’re calling a function with arguments that happen to be in a JSON document or URL arguments.

A RESTful service has a URI for each item in the inventory.

So, adding a new item would look like the example above.

POST /item HTTP/1.1
 
{
    "Item": {
          "name": "new item",
          "price": "9.99",
          "id": "1001"
      }
}    

But the similarities end there. Retrieving an item is always a GET:

GET /item/1001 HTTP/1.1   

Deleting is a DELETE:

DELETE /item/1001 HTTP/1.1  

Modifying an item is a PUT:

POST /inventory HTTP/1.1
 
{
    "Item": {
          "name": "new item",
          "price": "7.99",
          "id": "1001"
      }
}    

The difference is important. In REST, operations that use distinct HTTP actions. These verbs correspond directly to the activity on the data. GET, POST, PUT, DELETE and PATCH all have specific contracts. Most well-designed REST APIs also return specific HTTP codes, depending on the result of the request.

The critical point is that the URIs operate on the data, not on remote methods.

But there’s another reason why the resource model is essential.

REST vs RESTful and the Richardson Maturity Model

When you model your URIs after resources and use HTTP verbs you make your API predictable. Once developers know how you defined your resources, they can almost predict what the API looks like. Here again, the emphasis is on understanding the data, not the operations.

But even if you can’t make the API entirely predictable, you can document any REST service with hypertext. So, each item returned in the inventory app would contain links for deleting, modifying, or setting the inventory level of the resource. Fielding says that before a service is RESTful, it must provide hypertext media as part of the API.

Many sites don’t meet this requirement but are still called REST. Fact is, many sites break the rules in one way or another. So many that Leonard Richardson created a model breaks down REST into levels of compliance

We’ve already covered the source levels:

  • 0 – exporting an API over HTTP with methods called with arguments
  • 1 – Exporting resources instead of methods
  • 2 – Proper use of HTTP verbs
  • 3 – Exporting hypertext with objects that make all or part of the API discoverable.

Richardson’s model is his own, and it doesn’t map directly into Fielding’s spec. Since Fielding requires level three, he would say that most apps aren’t REST anyway.

The point is many services that we colloquially refer to as REST, technically aren’t.

REST vs RESTful: Does It Matter?

So, does the REST vs. RESTful comparison matter? Probably not. How well your architecture complies with an arbitrary standard isn’t as important with how well it suits your needs and can grow with your business.

The REST architectural pattern has many advantages. Fielding designed it for the web and, 18 years later, most of the constraints he had in mind are still with us. In 2000 we didn’t have Android or the iPhone. IE5 had 50% of the browser market share. It’s biggest rival was Firefox. But Fielding recognized what online applications needed and how web clients would evolve from HTML display engines into complete applications. The tools we use today have grown to suit REST, not the other way around.

Thank you for reading. Hope this tutorial will help you!