Table of Contents
...
outline | true |
---|
REST
Introduction
REST is not a standard, but a Web application development architectural style, which can be understood as a design pattern. REST-based HTTP, URI, XML and widely popular these existing protocols and standards, along with REST, HTTP protocol to obtain a more correct use. SOAP and WSDL-based Web services, REST model provides a more concise compared to realization.
REST API using the resource positioning, WEB service interface is provided externally and announced a series of URI parameters.
URI
Introduction
URI(Uniform Resource Identifier) is a string of some simple uniform (standardized) manner that identifies the resource
Description
Part Description
URI generally consists of three parts
- Named mechanism for accessing resources
- Storage resource host name
- The name of the resource itself, represented by the path. Typically, this string scheme (named URI namespace identifier) at the beginning of the following syntax: [scheme:] scheme-specific-part. URI scheme and the beginning of the colon, Scheme uppercase / lowercase letters beginning, followed by the empty or more uppercase / lowercase letters, numbers, plus, minus and dot. Colon and the scheme scheme-specific-part separated, and the scheme-specific-part syntax and semantics (meaning) is determined by the namespace URI.
A typical URI in the table below, including the protocol name, host name, port services, and other resources to address and query string:
...
Resource Address Description
Resource address is divided into ServiceType, ServiceName, Service Version, PathInfo four parts.
http(s)://[hostname][:port]/[ServiceType]/[ServiceName]/[Service Version]/[PathInfo]
ServiceType
Service Type?openoapi and openoui(UI)
ServicesName
Service Name, a globally unique
Recommended:
- For GSO, SDNO and NFVO, service name should include the project name as well as the microservice name to ensure uniqueness, example: 'sdno-l3vpnService'
- For O-Common and Common-Tosca, the project name is not necessary in the service name, example: 'catalog'
ServicesVersion
Service Version, requirements v + numbers, such as v1 v1.1, etc
PathInfo
Resource Path Information
ServiceType | ServiceName | ServiceVersion | PathInfo |
---|---|---|---|
openoapi | catalog | v1 | /servicetemplates |
openoapi | catalog | v1 | /servicetemplates/{serviceTemplateId} |
oepnoui | log | v1 | /info/syslogs |
oepnoui | log | v1 | /statisticinfo/syslogs |
Absolute URI and Relative URI
Absolute URI: In scheme (followed by a colon) at the beginning of the URI, for example http://www.cnn.com/index.html. It can be seen as an absolute URI reference to a resource in some way, and this way the environment is not dependent identifier appears.
Relative URI: Not in the scheme (followed by a colon) begins URI, such as articles / articles.html. You can put relative URI regarded as quoted in some way some resources, and in this way depends on the identifier appears environments.
Http Method
Operation Method
HTTP / 1.1 Protocol defines eight methods of CPC (sometimes called "action") to indicate a different mode of operation Resources Request-URI specified:
- OPTIONS :The method returns the server request for a particular resource supports HTTP. It can also be used to send to the Web server '\ *' request to test the WEB server supports.
- HEAD : Ask the server to ask for consistent response GET request, but the response body will not be returned. This method can be without having to transport the entire content, it can get included in the response message header meta-information.
- GET : Make a request to a specific resource. Note: GET method should not be used to generate the "side effects" of the operation, such as modifying the resource status. Idempotent
- POST : Submitting data to the specified resource for processing a request (such as submitting a form or uploading files). Data is included in the request body. POST requests may lead to the establishment and / or existing resources to new resource changes.
- PUT: To upload their content to the latest specified resource location.
- PATCH : Requests the server entity designated URI represented by the partial update. PATCH method should contain enough information for the server update requests. If the specified resource exists, the server can be updated and return the status code 200 (OK) or 204 (No Content). it similar to the processing with PUT method , if the specified resource does not exist, the server can create the resource. If the server resource is created, it should return the status code 201 (Created). If a resource to support PATCH method, then OPTIONS response Allow header can this be explained. The server can also use the Accept-Patch headers, lists media types the client can request its sending PATCH. Protocol specification recommends that media type should contain semantic information required to transfer part of the update to the server. json-patch (see https://tools.ietf.org/html/draft-pbryan-json-patch-04) is a proposed draft media types, partial updates required to support the operation expression.
- DELETE: Requests the server to delete * Request-URI * resources identified.
- TRACE : Requests the server returns a request it receives. The server returns a content-type of message or http context, which contains the complete request information. Clients can use the TRACE method, review the changes made to the message request message through a proxy and an intermediate layer to help diagnose problems.
- CONNECT: Reserved for the ability to connect to the pipeline mode proxy server.
Additional Properties
Safe
Use secure HTTP method for sending the request, it does not produce any side effects from the user side. This is not to say that security measures will not cause side effects, but that the user can use this method to safely initiate the request, do not worry about inadvertently modified the system state.
Idempotent
By Idempotent issued a request for resources with multiple requests the same effect. By definition, all security methods are idempotent. Some methods are not safe, but may also be idempotent. Similar security methods, using idempotent request does not guarantee that does not produce any side effects on the server side, but unrelated to these possible side effects and users.
Cachable
Cacheable ways to obtain a response to previous requests from the cache at a mid-tier caching.
...
When a request for a resource does not support the corresponding request method, the server should return the status code 405 (Method Not Allowed); when the server does not know or does not support the corresponding request method, it shall return a status code 501 (Not Implemented).
HTTP server should implement at least the GET and HEAD methods, other methods are optional. In addition to the above-described method, a specific HTTP server can also extend custom method.
...
Resource Address Design Specification
Service Description
- API Service
- Content service , static pages and js, css and other resources
...
Note: The version number before lowercase letter 'v'
For example:
...
URI Construction
RESTful APIs use Uniform Resource Identifiers (URIs) to address resources, ONAP projects should comply with a unified URI standard to implement the microservices.
- URI structure (Mandatory)
URI structure http://[host]:[port]/api/{service name}]/v{version number}/{resource}
The URI is comprised of a fixed base uri /api/{service name}]/v{version number} and the resource path. Only major version number is used in the URI. An example: http://127.0.0.1:8080/api/petstore/v1/pets/dogs CRUD function names should not be used in URIs. Instead, CRUD actions should be represented by HTTP methods. Below is the proposed methodology to implement CRUD operations in a RESTful API. (Recommended)
Resource POST GET PUT DELETE /api/petstore/v1/pets/dogs Create a new dog List dogs Replace dogs with new dogs(Bulk update) Delete all dogs /api/petstore/v1/pets/dogs/bailey Error Show dog If exist update dog else ERROR Delete dog Do not use:
/api/petstore/v1/pets/getalldogs
/api/petstore/v1/pets/createdog
/api/petstore/v1/pets/deletedog
- A trailing forward slash (/) should not be included in URIs (Mandatory)
A forward slash (/) adds no semantic value and may cause confusion. RESTful API’s should not expect a trailing slash and should not include them in the links that they provide to clients.
- Forward slash separator (/) must be used to indicate a hierarchical relationship (Mandatory)
- Use Hyphens (-) instead of Underscores (_) if separation of words is needed in the URI (May have conflict with SOL, TBD)
Underscores (_) can be hidden by the underline of URIs in browsers.
- Lowercase letters should be preferred in URI paths (Recommended)
When convenient, lowercase letters are preferred in URI paths since capital letters can sometimes cause problems. RFC 3986 defines URIs as case-sensitive except for the scheme and host components.
- File extensions should not be included in URIs (Recommended)
A REST API should not include artificial file extensions in URIs to indicate the format of a message’s entity body. Instead, they should rely on the media type, as communicated through the Content-Type header, to determine how to process the body’s content.
- A plural noun should be used for collection names (Mandatory)
For example, the URI for a collection of dog documents uses the plural noun form of its contained resources: /api/petstore/v1/pets/dogs - A singular noun should be used for document names (Mandatory)
For example, the URI for a single dog document would have the singular form: /api/petstore/v1/pets/dogs/bailey
Versioning
API is a public contract between a Server and a Consumer, so it's crucial to make sure the changes are backwards compatible. We need to introduce new versions of the API while still allowing old versions to be accessible when it's necessary. So a versioning mechanism should be considered.
- Semantic Versioning http://semver.org/ (Mandatory)
- The version in the swagger file and URI (Mandatory)
The main idea is that there are two kinds of versions:- Major version: The version used in the URI and denotes breaking changes to the API. Internally, a new major version implies creating a new API and the version number is used to route to the correct implementation.
- Minor and Patch versions: These are transparent to the client and used internally for backward-compatible updates. They should be reflected in the swagger files to inform clients about a new functionality or a bug fix.
For example, if the version of a RESTful API of an ONAP component is 1.3.2, the Info Object of swagger file should look like
Code Block |
---|
title: Swagger Sample App
description: This is a sample server Petstore server.
termsOfService: http://swagger.io/terms/
contact:
name: API Support
url: http://www.swagger.io/support
email: support@swagger.io
license:
name: Apache 2.0
url: http://www.apache.org/licenses/LICENSE-2.0.html
version: 1.3.2 |
The URI should look like: http://{host}/api/v1/pets
- Version discovery (Optional)
Need to be discussed: Should ONAP adopt a version discovery mechanism like OpenStack? :https://wiki.openstack.org/wiki/VersionDiscovery
HTTP response status codes
The server should always return the right HTTP status code to the client. (Recommended)
- Standard HTTP status codes
200 – OK – Everything is working
201 – OK – New resource has been created
204 – OK – The resource was successfully deleted
304 – Not Modified – The client can use cached data
400 – Bad Request – The request was invalid or cannot be served. The exact error should be explained in the error payload. E.g. „The JSON is not valid“
401 – Unauthorized – The request requires a user authentication
403 – Forbidden – The server understood the request but is refusing it or the access is not allowed.
404 – Not found – There is no resource behind the URI.
422 – Unprocessable Entity – Should be used if the server cannot process the entity, e.g. if an image cannot be formatted or mandatory fields are missing in the payload.
500 – Internal Server Error – API developers should avoid this error. If an error occurs in the global catch blog, the stracktrace should be logged and not returned as in the response.
- Use error payloads
All exceptions should be mapped in an error payload. Here is an example how a JSON payload should look like.
Code Block |
---|
{
"message": "Sorry, the requested resource does not exist",
"code": 34
} |
Need to be discussed: Should ONAP define a unified error response format across projects?
Security
- Token Based Authentication (Recommended)
Ideally, microservices should be stateless so the service instances can be scaled out easily and the client requests can be routed to multiple independent service providers. A token based authentication mechanism should be used instead of session based authentication - API-Token Authentication (Recommended)
ONAP is supposed to be accessed by third-party apps such as OSS/BSS, in the authentication process a user is not involved. API-Token can be used in such cases. - Centralized Authentication/Authorization (Recommended)
The MSB API Gateway can serve as the entry point to authenticate client requests and forwards them to the backend services, which might in turn invoke other services.
MSB doesn't do the authentication itself, instead, MSB can work with a security provider to provide centralized Authentication or ONAP with its pluggable architecture. - Use https for external communication for security reason
The MSB External API Gateway can translate the https request from the external systems to light weight http communication inside ONAP system. The individual projects don't have to handle the trivial details such as certification configuration and avoid the overhead of https inside ONAP system.
Multiple tenants support
TBD
API Documentation(Swagger)
- All the RESTful API must follow Swagger Specification for API documentation: http://swagger.io/specification (Recommended)
The ONAP-Components must provide swagger files for its RESTful API definitions, there are two possible approaches.- The developers write the Swagger file, then use CI system to generate the stub codes for implementation.
- The developers write the Swagger annotation in the source codeI, then use CI system to generate the Swagger file.
- The Swagger file should be placed under the base url of the service so the API definition could be discovered by clients or management tools at runtime. (Recommended)
For example, if the base url of peststore service is /api/petstore/v1/, the URL of swagger file should be /api/petstore/v1/Swagger.json
Appendix
Swagger Specification http://swagger.io/specification
Swagger UI https://swagger.io/swagger-ui/
Swagger code generator https://swagger.io/swagger-codegen/
Maven plugin to generate Swagger documents https://github.com/WASdev/tool.swagger.docgen
MSB Centralized Authentication & Authorization solution https://wiki.onap.org/download/attachments/3246982/Capture7.PNG?version=1&modificationDate=1495079131000&api=v2
Swagger SDK https://wiki.open-o.org/display/CLIEN/Swagger+SDK+for+Open-O
...
Use path variables to express the resource hierarchy
For example:
View a device information in topology:
http://127.0.0.1/openoapi/topo/v1/resources/{Resourcelocate id}
View a user information in safe module?
http://127.0.0.1/openoapi/sm/v1/users/{userid}
Path variable expression using punctuation non-hierarchical structure
- If you need to express non-hierarchical order is irrelevant, use a semicolon.
- If you need to express non-hierarchical order, use a commas.
- If the application requires the expression of more complex structures, you can define additional punctuation and semantics, but the comma and semicolon must be used to indicate the order of relations with non-hierarchical structure.
For example:
View all link information between two nes in topology:
http://127.0.0.1/openoapi/topo/v1/links/{ne id1};{ne id2}
View all link information from one ne to another ne in topology:
http://127.0.0.1/openoapi/topo/V1/links/{ne id1},{ne id2}
Use query variable expression algorithm (service) input
For example:
View a system log information
http://127.0.0.1/openoapi/log/v1/syslogs?id=101&filter=admin&count=50
Note: '&' In the URL is the only standard parameters of Http URL delimiters, do not denote any business meaning. Application needs its own resolution parameters of business meaning.
Use json variable expression algorithm (service) input
- POST request uses json object as a parameter input, you need to put inside the body, parser body when the server response.
- If the query parameter is too long GET request, allow POST GET equivalent use; This policy requires strict restrictions violate REST principles.
Exception Handling Design
JAX-RS2.0 defines the status code of the response javax.ws.rs.core.Response.Status and base exception class
javax.ws.rs.WebApplicationException, This exception contains the following sub-classes.
...