Translate

Wednesday 5 February 2020

An Introduction to REST and RESTful APIs

An Introduction to REST and RESTful APIs

REST is an acronym for Representational State Transfer — an almost meaningless description of the most-used web service technology! REST is a way for two computer systems to communicate over HTTP in a similar way to web browsers and servers.

Sharing data between two or more systems has always been a fundamental requirement of software development. For example, consider buying motor insurance. Your insurer must obtain information about you and your vehicle so they request data from car registration authorities, credit agencies, banks, and other systems. All this happens transparently in real time to determine whether a policy can be offered.

REST Example

Open the following link in your browser to request a random programming joke:

https://official-joke-api.appspot.com/jokes/programming/random

This is a public API implemented as RESTful web service (it follows REST conventions). Your browser will show an awful JSON-formatted programming joke, such as:

[
  {
    "id": 29,
    "type": "programming",
    "setup": "There are 10 types of people in this world...",
    "punchline": "Those who understand binary and those who don't"
  }
]

You could request the same URL and get a response using any HTTP client, such as curl:

curl "https://official-joke-api.appspot.com/jokes/programming/random"

HTTP client libraries are available in all popular languages and runtimes including Fetch in JavaScript and file_get_contents() in PHP. A JSON response is machine-readable so it can be parsed and output in HTML or any other format.

REST and the Rest

Various data communication standards have evolved over the years. You may have encountered standards including CORBA, SOAP, or XML-RPC, which usually established strict messaging rules.

REST was defined in 2000 by Roy Fielding and is considerably simpler. It's not a standard but a set of recommendations and constraints for RESTful web services. These include:

  1. Client-Server. SystemA makes an HTTP request to a URL hosted by SystemB, which returns a response.

    It's identical to how a browser works. The application makes a request for a specific URL. The request is routed to a web server that returns an HTML page. That page may contain references to images, style sheets, and JavaScript, which incur further requests and responses.

  2. Stateless. REST is stateless: the client request should contain all the information necessary to respond to a request. In other words, it should be possible to make two or more HTTP requests in any order and the same responses will be received.

  3. Cacheable. A response should be defined as cacheable or not.

  4. Layered. The requesting client need not know whether it’s communicating with the actual server, a proxy, or any other intermediary.

Creating a RESTful Web Service

A RESTful web service request contains:

  1. An Endpoint URL. An application implementing a RESTful API will define one or more URL endpoints with a domain, port, path, and/or querystring — for example, https://mydomain/user/123?format=json.

  2. The HTTP method. Differing HTTP methods can be used on any endpoint which map to application create, read, update, and delete (CRUD) operations:

    HTTP method CRUD Action
    GET read returns requested data
    POST create creates a new record
    PUT or PATCH update updates an existing record
    DELETE delete deletes an existing record

    Examples:

    • a GET request to /user/ returns a list of registered users on a system
    • a POST request to /user/123 creates a user with the ID 123 using the body data
    • a PUT request to /user/123 updates user 123 with the body data
    • a GET request to /user/123 returns the details of user 123
    • a DELETE request to /user/123 deletes user 123
  3. HTTP headers. Information such as authentication tokens or cookies can be contained in the HTTP request header.

  4. Body Data. Data is normally transmitted in the HTTP body in an identical way to HTML <form> submissions or by sending a single JSON-encoded data string.

The Response

The response payload can be whatever is practical: data, HTML, an image, an audio file, and so on. Data responses are typically JSON-encoded, but XML, CSV, simple strings, or any other format can be used. You could allow the return format to be specified in the request — for example, /user/123?format=json or /user/123?format=xml.

An appropriate HTTP status code should also be set in the response header. 200 OK is most often used for successful requests, although 201 Created may also be returned when a record is created. Errors should return an appropriate code such as 400 Bad Request, 404 Not Found, 401 Unauthorized, and so on.

Other HTTP headers can be set including the Cache-Control or Expires directives to specify how long a response can be cached before it’s considered stale.

However, there are no strict rules. Endpoint URLs, HTTP methods, body data, and response types can be implemented as you like. For example, POST, PUT, and PATCH are often used interchangeably so any will create or update a record.

REST "Hello World" Example

The following code creates a RESTful web service using the Node.js Express framework. A single /hello/ endpoint responds to GET requests.

Ensure you have Node.js installed, then create a new folder named restapi. Create a new package.json file within that folder with the following content:

{
  "name": "restapi",
  "version": "1.0.0",
  "description": "REST test",
  "scripts": {
    "start": "node ./index.js"
  },
  "dependencies": {
    "express": "4.17.1"
  }
}

Run npm install from the command line to fetch the dependencies, then create an index.js file with the following code:

// simple Express.js RESTful API
'use strict';

// initialize
const
  port = 8888,
  express = require('express'),
  app = express();

// /hello/ GET request
app.get('/hello/:name?', (req, res) =>
  res.json(
    { message: `Hello ${req.params.name || 'world'}!` }
  )
);

// start server
app.listen(port, () =>
  console.log(`Server started on port ${port}`);
);

Launch the application from the command line using npm start and open http://localhost:8888/hello/ in a browser. The following JSON is displayed in response to the GET request:

{
  "message": "Hello world!"
}

The API also allows a custom name, so http://localhost:8888/hello/everyone/ returns:

{
  "message": "Hello everyone!"
}

The post An Introduction to REST and RESTful APIs appeared first on SitePoint.



No comments:

Post a Comment