REST API for Microservices Overview

Machine Learning Technology Artificial Intelligence Technology Natural Language Processing Technology   Semantic Web Technology Search Technology DataBase Technology Ontology Technology Digital Transformation Technology User Interface and DataVisualization Workflow & Services Navigation of this blog Algorithm Clojure Microservice

Summary

From Microservices with Clojure. In the previous article, I gave an overview of microservices architecture. In this article, I will give an overview of the REST API for microservices.

REST Overviews

REST stands for representational state transfer and defines an architectural style of distributed hypermedia systems. applications that support REST do not store any information about the client’s state on the server side. Such applications require the client to maintain state itself and transfer state between the client and server using a REST-style implementation, such as an HTTP API exposed by the application. synchronize the client and server by querying the server for the latest state and expressing the same state on the client side.

The state of an application is defined by the state of entities in the system. Entities can be associated with the concept of resources in the REST architecture. Resources are an important abstraction of information in REST. It is a conceptual mapping to a set of entities defined by resource identifiers; any information that can be named or is subject to a resource identifier in REST can be a resource. For example, a consumer is a resource for a service consumer service and an order is a resource for an order service.

Resource identifiers in REST are defined as API endpoints mapped to HTTP URIs. URIs point to one or more resources, allowing the caller to perform operations on the resource, as shown in the previous image. All operations supported by REST are stateless, and no client state is stored on the server side; the stateless nature of the REST API helps create services that scale horizontally without relying on shared state.
The REST style is well suited for microservices that communicate directly and build synchronous APIs to access entities. Each entity managed by a microservice can be mapped directly to REST’s notion of resources.

The concept of REST was defined by Roy Fielding in 2000 as part of his doctoral dissertation entitled “Architectural Styles and the Design of Network-based Software Architectures” (https://www.ics. uci.edu/~fielding/pubs/dissertation/fielding_dissertation_2up.pdf). RESTful systems are client-server, stateless, cacheable, layered systems, code on demand, unified It adheres to the six guiding principles of interfaces (https://en.wikipedia.org/wiki/ Representational_state_transfer#Architectural_constraints ).

RESTful API

Web service APIs that conform to the REST architecture are called RESTful APIs. Many microservices implement an HTTP-based RESTful API that is stateless and has a base URI and media type (https://en.wikipedia.org/wiki/Media_type) for resource representation. They also support predefined standard operations mapped to HTTP methods such as GET, POST, PUT, and DELETE.
For example, as shown in the following table, the Order service defines API /orders to allow access to the orders it holds. It can support GET methods to retrieve all orders or to retrieve a specific order by specifying the order ID. It also allows the client to create a new order using the POST method or to create an order with a specific ID using the PUT method. Similarly, the PUT method can be supported to update order details and the DELETE method to delete an order by explicitly specifying the order ID.

GET, PUT, POST, and DELETE will be the most widely used HTTP methods in the RESTful API. Other methods include HEAD, OPTIONS, PATCH, TRACE, and CONNECT (https://en. wikipedia.org/wiki/Hypertext_Transfer_Protocol#Request_methods ). Each request sent to the URI generates a response that may be HTML, JSON, XML, or any defined format. JSON is the preferred format for microservices that handle the core operations of the application. For example, the response generated by the Order service’s RESTful API may contain a JSON object of order details or a JSON array of orders, where each order is represented as a key-value pair JSON object containing order details.

Status codes

The status code is important for the client to understand the result of the request and take the necessary action on the response. A successful request will return a response expressing the necessary resources, while a failed request will instead generate a response expressing an error. The status code helps the client better understand the response and take the necessary action on the client side.
All microservices with RESTful APIs must support appropriate HTTP status codes (https:/ /en.wikipedia.org/wiki/List_of_HTTP_status_codes) and send them to the client The client must be sent based on the result of the requested operation. Some of the status codes that must be implemented by all microservice APIs are listed below.

The REST API must implement the above status codes. Other status codes may also be used by the API. To see all defined status codes, see the HTTP Status Code Guide.

Naming conventions

The REST API must be structured around the system’s resources and be easily understood just by looking at the URI The URI must focus on one resource type at a time, with operations mapped to the HTTP request method The URI must also contain It can have one or more associated resources that can be nested.
Good examples of URIs are /users, /consumers, /orders, /services, not /getusers, /showorders, etc. The basic rule for defining API URIs is to target nouns as resources and verbs as HTTP methods. The basic rule for defining an API URI is to target nouns as resources and verbs as HTTP methods For example, instead of creating a URI /getusers, it is recommended to prepare a URI /users and use the HTTP method GET. Similarly, instead of /showorders, the URI GET /orders should be created to provide the client with all orders contained in the response. guidelines for naming URIs are further explained in the following figure.

It is recommended that all APIs use only HTTPS-based URIs and always use SSL (https://en.wikipedia.org/wiki/Transport_Layer_ Security). In order to upgrade the API from time to time without disrupting the integration with existing services, API versioning is required. a major version may be used as a prefix for all API endpoints to specify the API version. Subversion should not be added to the URI. If necessary, they can be specified using custom header parameters.

Versions may also be introduced in media types. It is perfectly acceptable to include subversion in a media type. Versions may contain changes that are destructive to the client, but it is recommended that backward compatibility be maintained as much as possible.

URIs may also include application qualifiers that classify API endpoints according to the component or business being covered. Each URI must focus on a single resource type, and its name must be used in the plural. To retrieve a specific resource of a given type, an ID must be appended to the URI. Below is an example of a URI that follows a straightforward naming convention.

Using RESTful APIs via cURL

cURL can be a command line utility for transferring data using various protocols such as HTTP and HTTPS. cURL is widely used to experiment with RESTful APIs using its command line interface. For example, let’s look at an example that uses the API provided by MetaWeather (https://www. metaweather.com/api/) to query a location and retrieve its weather information. Since this is a public API that manages weather information for well-known locations, it only allows GET requests to retrieve resource details and does not allow the creation or updating of resources.

To retrieve the weather for a location, the MetaWeather application needs a system-defined resource ID. To retrieve the resource ID, MetaWeather provides a search API to search for resources by search query. The search API uses the GET method with the query in the URL parameter of the request and returns a JSON response with resources matching the query, as shown here.

% curl -XGET
   "https://www.metaweather.com/api/location/search/?query=bangalore"
   [{"title":"Bangalore","location_type":"City","woeid":2295420,"latt_long":"1
   2.955800,77.620979"}]

The woeid field in the response is a resource ID required by the weather API that can be used to retrieve weather details for the queried location.

% curl -XGET "https://www.metaweather.com/api/location/2295420/"
   {
    "title": "Bangalore",
    "location_type": "City",
    "woeid": 2295420,
    "latt_long": "12.955800,77.620979",
    "timezone": "Asia/Kolkata",
    "time": "2017-10-24T21:06:34.146240+05:30",
    "sun_rise": "2017-10-24T06:11:13.036505+05:30",
    "sun_set": "2017-10-24T17:56:02.483163+05:30",
    "timezone_name": "LMT",
    "parent": {
      "title": "India",
      "location_type": "Country",
      "woeid": 23424848,
      "latt_long": "21.786600,82.794762"
    },
    "consolidated_weather": [
      {
        "id": 6004071454474240,
        "weather_state_name": "Heavy Cloud",
        "weather_state_abbr": "hc",
        "wind_direction_compass": "NE",
        "created": "2017-10-24T15:10:08.268840Z",
        "applicable_date": "2017-10-24",
        "min_temp": 18.458000000000002,
        "max_temp": 29.392000000000003,
        "the_temp": 30.0,
        "wind_speed": 1.9876466767411649,
        "wind_direction": 51.745585344396069,
        "air_pressure": 969.60500000000002,
        "humidity": 63,
        "visibility": 11.150816730295077,       "predictability": 71
      },
... ],
    "sources": [
      {
        "title": "BBC",
        "slug": "bbc",
        "url": "http://www.bbc.co.uk/weather/",
        "crawl_rate": 180
},
... ]
}

The MetaWeather application API also supports the OPTIONS method, which can be used to find out more about the API. For example, sending a request to the same search API with the OPTIONS HTTP method will provide the necessary details in the response.

% curl -XOPTIONS
   "https://www.metaweather.com/api/location/search/?query=bangalore"
   {"name":"Location
   Search","description":"","renders":["application/json"],"parses":["applicat
   ion/json","application/x-www-form-urlencoded","multipart/form-data"]}

The MetaWeather application will also return the appropriate status code and message in response to an invalid resource ID.

% curl -v -XGET "https://www.metaweather.com/api/location/0/"
   ...
   * Trying 172.217.26.179...
   * Connected to www.metaweather.com (172.217.26.179) port 443 (#0)
   ...
* compression: NULL
* ALPN, server accepted to use http/1.1
> GET /api/location/0/ HTTP/1.1
> Host: www.metaweather.com
> User-Agent: curl/7.47.0
> Accept: */*
>
< HTTP/1.1 404 Not Found
< x-xss-protection: 1; mode=block
< Content-Language: en
< x-content-type-options: nosniff
< strict-transport-security: max-age=2592000; includeSubDomains < Vary: Accept-Language, Cookie
< Allow: GET, HEAD, OPTIONS
< x-frame-options: DENY
< Content-Type: application/json
< X-Cloud-Trace-Context: 507eec2981a7028e50e596fcb651acb7;o=1 < Date: Tue, 24 Oct 2017 16:07:36 GMT
< Server: Google Frontend
< Content-Length: 23
<
* Connection #0 to host www.metaweather.com left intact {"detail":"Not found."}
Summary

In this section, we discussed the concept of REST and how to design a RESTful API with an easy-to-understand naming convention. We also discussed what to use and when for the various request methods and status codes again, and finally, we reviewed the Helping Hands application and listed the REST APIs that are needed for the application across microservices.
In the next article, we discuss Pedestal (http:// pedestal.io/), a Clojure framework used to design microservices for the Helping Hands application. Pedestal is also used to expose REST APIs for various microservice operations.

In the next article, we will discuss the implementation of REST API for concrete microservices with Clojure using Pedestal.

コメント

タイトルとURLをコピーしました