# Table of Contents - [Contract | API Guidelines](#contract-api-guidelines) - [JSON | API Guidelines](#json-api-guidelines) - [Version Control System | API Guidelines](#version-control-system-api-guidelines) - [Robustness | API Guidelines](#robustness-api-guidelines) - [Minimal API Surface | API Guidelines](#minimal-api-surface-api-guidelines) - [Protocol | API Guidelines](#protocol-api-guidelines) - [Immutability | API Guidelines](#immutability-api-guidelines) - [TLS | API Guidelines](#tls-api-guidelines) - [Introduction | API Guidelines](#introduction-api-guidelines) - [Rules for Extending | API Guidelines](#rules-for-extending-api-guidelines) - [Introduction | API Guidelines](#introduction-api-guidelines) - [API Design Platform | API Guidelines](#api-design-platform-api-guidelines) - [Testing | API Guidelines](#testing-api-guidelines) - [Status Codes | API Guidelines](#status-codes-api-guidelines) - [Common Data Types | API Guidelines](#common-data-types-api-guidelines) - [Separate Concerns | API Guidelines](#separate-concerns-api-guidelines) - [Tooling | API Guidelines](#tooling-api-guidelines) - [OpenAPI Specification | API Guidelines](#openapi-specification-api-guidelines) - [HTTP | API Guidelines](#http-api-guidelines) - [Content Negotiation | API Guidelines](#content-negotiation-api-guidelines) - [Pagination | API Guidelines](#pagination-api-guidelines) - [Message | API Guidelines](#message-api-guidelines) - [Long Running Tasks | API Guidelines](#long-running-tasks-api-guidelines) - [Application | API Guidelines](#application-api-guidelines) - [Corporate Data Model | API Guidelines](#corporate-data-model-api-guidelines) - [Message Formats | API Guidelines](#message-formats-api-guidelines) - [API First | API Guidelines](#api-first-api-guidelines) - [Polling | API Guidelines](#polling-api-guidelines) - [Core REST Principles | API Guidelines](#core-rest-principles-api-guidelines) - [Common Data Types | API Guidelines](#common-data-types-api-guidelines) - [Security | API Guidelines](#security-api-guidelines) - [Design Maturity | API Guidelines](#design-maturity-api-guidelines) - [Batch Operations | API Guidelines](#batch-operations-api-guidelines) - [Problem Detail | API Guidelines](#problem-detail-api-guidelines) --- # Contract | API Guidelines An approved API Design, represented by its API Description or schema, **MUST** represent the **contract** between API stakeholders, implementers, and consumers. An update to the corresponding contract (API Design) **MUST** be implemented and approved before any change to an API is made. [PreviousAPI First](/api-guidelines/general-guidelines/api-first) [NextImmutability](/api-guidelines/general-guidelines/c_immutability) Last updated 9 months ago --- # JSON | API Guidelines Any JSON-based message **MUST** conform to the following rules: 1. All JSON field names **MUST** follow the [Naming Conventions](/api-guidelines/rest-api-guidelines/evolution/naming-conventions) (`camelCase`, American English, etc.) 2. Field names **MUST** be ASCII alpha num characters, underscore (`_`) or dollar sign (`$`) 3. Boolean fields **MUST NOT** be of `null` value 4. Fields with `null` value **SHOULD** be omitted 5. Empty arrays and objects **SHOULD NOT** be `null` (use `[]` or `{}` instead) 6. Array field names **SHOULD** be plural (e.g. `"orders": []`) [](#validation) Validation ------------------------------- All API designers **MUST** validate the definition of the payloads in requests/responses with the [JSON Schema](https://json-schema.org/) for the defined structure prior to the publication of the API Contract in SwaggerHub. The publication of the JSON schema corresponding to the expected payloads in the bodies of requests and responses **SHOULD** be kept up to date according to the evolution of the API. [PreviousRules for Extending](/api-guidelines/general-guidelines/rules-for-extending) [NextSecurity](/api-guidelines/general-guidelines/security) Last updated 4 years ago --- # Version Control System | API Guidelines Every API design **SHOULD** be stored in a Version Control System (e.g., Bitbucket, GitHub). Where possible the API design **SHOULD** be stored in the **same** repository as the API implementation. [PreviousCommon Data Types](/api-guidelines/general-guidelines/d_data_types) [NextMinimal API Surface](/api-guidelines/general-guidelines/minimal-api-surface) Last updated 9 months ago --- # Robustness | API Guidelines Every API implementation and API consumer **MUST** follow Postel's law: > _Be conservative in what you send, be liberal in what you accept._ > > _–_ [_John Postel_](https://en.wikipedia.org/wiki/Robustness_principle) That is, send the necessary minimum and be as tolerant as possible while consuming another service ([tolerant reader](https://martinfowler.com/bliki/TolerantReader.html) ). [PreviousImmutability](/api-guidelines/general-guidelines/c_immutability) [NextCommon Data Types](/api-guidelines/general-guidelines/d_data_types) Last updated 9 months ago --- # Minimal API Surface | API Guidelines Every API design **MUST** aim for a minimal API surface without sacrificing on product requirements. API design **SHOULD NOT** include unnecessary resources, relations, actions or data. API design **SHOULD NOT** add functionality until deemed necessary ([YAGNI principle](https://martinfowler.com/bliki/Yagni.html) ). [PreviousVersion Control System](/api-guidelines/general-guidelines/version-control-system) [NextRules for Extending](/api-guidelines/general-guidelines/rules-for-extending) Last updated 6 years ago --- # Protocol | API Guidelines This section outlines the protocol-level semantics and guidelines. [PreviousTesting](/api-guidelines/rest-api-guidelines/core-principles/testing) [NextHTTP](/api-guidelines/rest-api-guidelines/protocol/http) Last updated 6 years ago --- # Immutability | API Guidelines After agreement with the stakeholders the contract **MUST** be published in the API registry in order to make it (that version) immutable. The API registry acts as a central location for storing and accessing all published APIs. [PreviousContract](/api-guidelines/general-guidelines/contract) [NextRobustness](/api-guidelines/general-guidelines/robustness) Last updated 9 months ago --- # TLS | API Guidelines Every API **MUST** require secure connections with **TLS 1.2**. That is, an API using the HTTP protocol **MUST** use **HTTPS**. Any non-TLS requests **SHOULD** be ignored. In **HTTP** environments where this is not possible, a non-TLS request **SHOULD** result in the **403 Forbidden** response. [PreviousHTTP](/api-guidelines/rest-api-guidelines/protocol/http) [NextSeparate Concerns](/api-guidelines/rest-api-guidelines/protocol/separate-concerns) Last updated 6 years ago --- # Introduction | API Guidelines [](#adidas-general-api-guidelines) adidas General API Guidelines --------------------------------------------------------------------- In the scope of a company, organization or team, the document known as guidelines is a set of best practices or hints provided by a group of subject matter experts in that particular technology. The most important aspects of it: * Help to create a standardized way of completing specific tasks, making outcome more predictable and alike * Help to identify do's and dont's with regards to a specific technology or tool * Help to avoid gotchas or problems related with company specifics * Gather the knowledge of several Subject Matter Experts and prevent others for falling in frequent caveats or mistakes This is a set of general rules and recommendations that have to be followed along the entire API lifecycle of any API regardless of its type. **Note** In any case, the content in the guidelines should be taken as recommendations, not something that needs to be done in a mandatory way. [Previousadidas API Guidelines](/api-guidelines) [NextAPI First](/api-guidelines/general-guidelines/api-first) Last updated 9 months ago --- # Rules for Extending | API Guidelines Any modification to an existing API **MUST** avoid breaking changes and **MUST** maintain backward compatibility. In particular, any change to an API **MUST** follow the following **Rules for Extending**: 1. **You MUST NOT take anything away** (related: [Minimal Surface Principle](/api-guidelines/general-guidelines/minimal-api-surface) , [Robustness Principle](/api-guidelines/general-guidelines/robustness) ) 2. **You MUST NOT change processing rules** 3. **You MUST NOT make optional things required** 4. **Anything you add MUST be optional** (related [Robustness Principle](/api-guidelines/general-guidelines/robustness) ) > NOTE: These rules cover also renaming and change to identifiers (URIs). Names and identifiers should be stable over the time including their semantics. [PreviousMinimal API Surface](/api-guidelines/general-guidelines/minimal-api-surface) [NextJSON](/api-guidelines/general-guidelines/json) Last updated 6 years ago --- # Introduction | API Guidelines [](#adidas-rest-api-guidelines) adidas REST API Guidelines --------------------------------------------------------------- Adidas REST API Guidelines define standards and guidelines for building REST APIs at adidas. **These Guidelines have to be followed in addition to the Adidas** [**General API Guidelines.**](/api-guidelines/general-guidelines/general-guidelines) The REST API Guidelines are further split into the following parts: * **Core Principles** REST API Guidelines Core Principles defines the rules that **MUST** be followed at throughout the full API lifecycle. * **Functionality Guidelines** * \*\*\*\*[**Protocol level**](/api-guidelines/rest-api-guidelines/protocol) \*\*\*\* Protocol guidelines define the protocols used within the organization. * \*\*\*\*[**Message level**](/api-guidelines/rest-api-guidelines/message) \*\*\*\* The Message guidelines define the structure and semantics of messages used to exchange information. * \*\*\*\*[**Application level**](/api-guidelines/rest-api-guidelines/application) The Application guidelines define the definition and use of application-specific semantics. * **Quality Guidelines** Evolution and Execution guidelines define the rules for achieving the desired architectural qualities of systems. * \*\*\*\*[**Evolution**](/api-guidelines/rest-api-guidelines/evolution) \*\*\*\* Evolution qualities governance, such as testability, maintainability, extensibility, and scalability. * \*\*\*\*[**Execution**](/api-guidelines/rest-api-guidelines/execution) \*\*\*\* Execution qualities governance, such as security and usability. * **Guides** Guides and materials supporting the REST API Guidelines * **API Clients** Section dedicated to consumers of adidas APIs [PreviousTooling](/api-guidelines/general-guidelines/n_tooling) [NextCore REST Principles](/api-guidelines/rest-api-guidelines/core-principles) Last updated 4 years ago --- # API Design Platform | API Guidelines 1. [SwaggerHub](https://design.api.3stripes.io/) is the primary platform supporting [API first approach](/api-guidelines/general-guidelines/api-first) . SwaggerHub **MUST** be used during API Design. 2. Every API description **MUST** be stored in [SwaggerHub](https://design.api.3stripes.io/) under the adidas team. 3. SwaggerHub **MUST** be the **single source of truth** to learn about existing APIs within the organization. > NOTE: SwaggerHub supports API-first approach in multiple ways: For example, it validates API description for correctness and automatically generates API documentation to drive the discussion between stakeholders. (No more emails with API description flying between stakeholders) [PreviousOpenAPI Specification](/api-guidelines/rest-api-guidelines/core-principles/openapi-specification) [NextDesign Maturity](/api-guidelines/rest-api-guidelines/core-principles/design-maturity) Last updated 2 years ago --- # Testing | API Guidelines [](#dredd) DREDD --------------------- Every API description (contract) using HTTP(S) protocol **MUST** be tested against its API implementation. The tests **MUST** be executed using the [Dredd testing framework](https://github.com/apiaryio/dredd) . In addition to local runs, the tests **SHOULD** be an integral part the API implementation's CI/CD pipeline. The CI/CD pipeline **SHOULD** be configured to run the test whenever there is a change to either API description (contract) or its implementation. [](#pact) PACT ------------------- Every adidas **CORE** API **MUST** be tested additionally applying Consumer Driven Contract Testing principles. The tests **MUST** be executed using the [PACT contract testing tool](https://docs.pact.io/) . PACT tests **MUST** use adidas [PACT-Broker](http://pact.ati.adidas.com/) to store results and evidences. In addition to local runs, PACT tests **SHOULD** be an integral part of the API implementation's CI/CD pipeline. The CI/CD pipeline **SHOULD** be configured to run the test whenever there is a change to either API description (contract) or its implementation. Using Consumer Driven Contract Testing with PACT is _not mandatory_ for adidas **NON-CORE** APIs, but strongly recommended due to the advantages this approach brings. It will be also a proof of our Software Engineering practices maturity. More information, guides and seeds about how to use PACT can be found on (internal link)[adidas Consumer Driven Contract Testing guide](https://tools.adidas-group.com/confluence/display/DSBP/adidas+Consumer+Driven+Contract+Testing+guide) page. [PreviousDesign Maturity](/api-guidelines/rest-api-guidelines/core-principles/design-maturity) [NextProtocol](/api-guidelines/rest-api-guidelines/protocol) Last updated 5 years ago --- # Status Codes | API Guidelines Every API **MUST** use the appropriate [HTTP Status Codes](https://github.com/for-GET/know-your-http-well/blob/master/status-codes.md) to communicate the result of a request operation. Every API designer, implementer and consumer **MUST** understand the semantic of the HTTP Status Code she is using. At a minimum everyone **MUST** be familiar with the semantics of ["Common" HTTP Status Codes](https://github.com/for-GET/know-your-http-well/blob/master/status-codes.md#common) . [](#example) Example ------------------------- [](#use-codes-4xx-or-5xx-to-communicate-errors) Use Codes 4xx or 5xx to Communicate Errors ----------------------------------------------------------------------------------------------- The 4xx range concerns errors in the API Consumer/Client side, while 5xx range concerns errors in the upstream/backend service or the API implementation. A request: Copy GET /orders/1234 HTTP/1.1 ... resulting in the **200 OK** response when the requested resource (as identified by request URI) couldn't be found: Copy HTTP/1.1 200 OK Content-Type: application/json ... { "code": "NOT_FOUND_ERR_CODE" "message" "Order 1234 wasn't found" } is **not acceptable**. Instead Copy HTTP/1.1 404 Not Found ... should be returned. [](#recommended-reading) Recommended Reading ------------------------------------------------- * [How to Think About HTTP Status Codes](https://www.mnot.net/blog/2017/05/11/status_codes) [PreviousRequest Methods](/api-guidelines/rest-api-guidelines/protocol/use-appropriate-methods) [NextMessage](/api-guidelines/rest-api-guidelines/message) Last updated 8 months ago * [Example](#example) * [Use Codes 4xx or 5xx to Communicate Errors](#use-codes-4xx-or-5xx-to-communicate-errors) * [Recommended Reading](#recommended-reading) --- # Common Data Types | API Guidelines The API types **MUST** adhere to the formats defined below: Data type Standard Example Date and Time [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) 2017-06-21T14:07:17Z (Always use UTC) Date [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) 2017-06-21 Duration [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) P3Y6M4DT12H30M5S Time interval [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) 2007-03-01T13:00:00Z/2008-05-11T15:30:00Z Timestamps [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) 2017-01-01T12:00:00Z Language Codes [ISO 639](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) en <-> English Country Code [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) DE <-> Germany Currency [ISO 4217](https://en.wikipedia.org/wiki/ISO_4217) EUR <-> Euro [PreviousRobustness](/api-guidelines/general-guidelines/robustness) [NextVersion Control System](/api-guidelines/general-guidelines/version-control-system) Last updated 9 months ago --- # Separate Concerns | API Guidelines Every API using HTTP/S **MUST** precisely follow the concern separation of an HTTP message: 1. A _resource identifier_–URI **MUST** be used to indicate **identity** only 2. _HTTP request method_ **MUST** be used to communicate the **action semantics** (intent and safety) 3. _HTTP response status_ code **MUST** be used to communicate the **information about the result** of the attempt to understand and satisfy the request 4. _HTTP message body_ **MUST** be used to transfer the **message content** 5. _HTTP message headers_ **MUST** be used to transfer the **metadata** about the message and its content 6. _URI query parameter_ **SHOULD NOT** be used to transfer metadata [](#example-1) Example 1 ----------------------------- The rule > A resource identifier–URI **MUST** be used to indicate identity only implies there **MUST NOT** be any information about the representation media type, version of the resource or anything else in the URI. For example, URIs `/greeting.json` or `/v2.1.3/greeting` are **illegal** as they are not used for identification of a resource only but they convey the information about representation format or version. URIs are not meant to carry any other information but the identifier of the resource. [](#example-2) Example 2 ----------------------------- The rule > HTTP message body MUST be used to transfer the message content Implies an HTTP GET request **MUST NOT** use HTTP message body to identify the resource. For example a request: Copy GET /greeting HTTP/1.1 Content-Type: application/json ... { "filter": "string" "depth": 3 } is **not acceptable** (ignoring the fact that HTTP GET method shouldn't have the body). To express identity use URI and query parameters instead e.g. `/greeting?filter=string&depth=3`. > _Keep things simple while designing by separating the concerns between the different parts of the request and response cycle. Keeping simple rules here allows for greater focus on larger and harder problems._ > > _Requests and responses will be made to address a particular resource or collection. Use the path to indicate identity, the body to transfer the contents and headers to communicate metadata. Query params may be used as a means to pass header information also in edge cases, but headers are preferred as they are more flexible and can convey more diverse information._ > > _–_ [_Heroku HTTP API Design Guide_](https://geemus.gitbooks.io/http-api-design/content/en/foundations/separate-concerns.html) [PreviousTLS](/api-guidelines/rest-api-guidelines/protocol/tls) [NextRequest Methods](/api-guidelines/rest-api-guidelines/protocol/use-appropriate-methods) Last updated 8 months ago --- # Tooling | API Guidelines The current platform available in adidas to design, host, and render APIs specifications is [Swaggerhub](https://design.api.3stripes.io/) . Every API specification **MUST** be hosted in Swaggerhub under the _adidas_ organization. [PreviousSecurity](/api-guidelines/general-guidelines/security) [NextIntroduction](/api-guidelines/rest-api-guidelines/rest) Last updated 9 months ago --- # OpenAPI Specification | API Guidelines Every API **MUST** be described using an API description format. The API description format used **MUST** be the [OpenAPI Specification (formerly known as Swagger Specification) version 2.0](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md) OR the [OpenAPI Specification (formerly known as Swagger Specification) version 3.0.x](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.3.md) . Every API description **MUST** be published in adidas [API design platform](/api-guidelines/rest-api-guidelines/core-principles/design-platform) and it **SHOULD** be stored in version control system (Bitbucket, GitHub) in the same repository as the API implementation. [](#language) Language --------------------------- The API description **MUST** be written in **American English**. [PreviousCore REST Principles](/api-guidelines/rest-api-guidelines/core-principles) [NextAPI Design Platform](/api-guidelines/rest-api-guidelines/core-principles/design-platform) Last updated 8 months ago --- # HTTP | API Guidelines Every API MUST support [HTTP/1.1](https://tools.ietf.org/html/rfc7230) and **MUST** adhere to its **semantic**. [](#http-protocol-quick-start) HTTP Protocol Quick Start ------------------------------------------------------------- The understanding of HTTP starts with the understanding of [HTTP message](https://developer.mozilla.org/en-US/docs/Web/HTTP/Messages) and its routing. Once you are familiar with the **HTTP message structure** learn about the **HTTP request methods**, **HTTP response status codes** and **HTTP headers**. Each HTTP request method, status code, and header have its semantics defined, and every API **MUST** strictly adhere to it. Follow the [Robustness Principle](/api-guidelines/general-guidelines/robustness) . Use only the HTTP request methods, response codes and HTTP headers you understand, be liberal in accepting others. [](#know-http) Know HTTP ----------------------------- The following documents are great overview of the HTTP protocol and related standards: * [HTTP Headers](https://github.com/for-GET/know-your-http-well/blob/master/headers.md) * [HTTP Request Methods](https://github.com/for-GET/know-your-http-well/blob/master/methods.md) * [HTTP Response Status Codes](https://github.com/for-GET/know-your-http-well/blob/master/status-codes.md) * [HTTP Link Relations](https://github.com/for-GET/know-your-http-well/blob/master/relations.md) Alternatively, you can download HTTP cheat sheets at [HTTP posters](https://github.com/bigcompany/know-your-http) . [](#rfcs) RFCs ------------------- The HTTP protocol semantics is defined in the following RFCs: > 1. [RFC 7230, HTTP/1.1: Message Syntax and Routing](https://tools.ietf.org/html/rfc7230) > > 2. [RFC 7231, HTTP/1.1: Semantics and Content](https://tools.ietf.org/html/rfc7231) > > 3. [RFC 7232, HTTP/1.1: Conditional Requests](https://tools.ietf.org/html/rfc7232) > > 4. [RFC 7233, HTTP/1.1: Range Requests](https://tools.ietf.org/html/rfc7233) > > 5. [RFC 7234, HTTP/1.1: Caching](https://tools.ietf.org/html/rfc7234) > > 6. [RFC 7235, HTTP/1.1: Authentication](https://tools.ietf.org/html/rfc7234) > [PreviousProtocol](/api-guidelines/rest-api-guidelines/protocol) [NextTLS](/api-guidelines/rest-api-guidelines/protocol/tls) Last updated 6 years ago --- # Content Negotiation | API Guidelines Every API **MUST** implement and every API Consumer **MUST** use the [HTTP content negotiation](https://tools.ietf.org/html/rfc7231#section-3.4) where a representation of a resource is requested. > NOTE: The content negotiation plays the key role in evolving an API, **change management and versioning**. [](#example) Example ------------------------- A client is programmed to understand the `application/vnd.example.resource+json; version=2` message format semantics. The client requests a representation of the `/greeting` resource in desired the media type (including its version) from the server: Copy GET /greeting HTTP/1.1 Accept: application/vnd.example.resource+json; version=2 ... The server can provide only a newer version of the requested media type `version=2.1.3`. But since the newer version is backward compatible with the requested `version=2` (related: Changes & Versioning) it can satisfy the request and responds: Copy HTTP/1.1 200 OK Content-Type: application/vnd.example.resource+json; version=2.1.3 ... > NOTE: A server that doesn't have the requested representation media type available **MUST** respond with the HTTP Status Code **406 Not Acceptable**. > > NOTE: A server **MAY** have multiple choices available and **MAY** respond with the **300 Multiple Choices** response. In which case client **SHOULD** choose from the presented choices. > > You can read more about content negotiation at [MDN Content negotiation](https://developer.mozilla.org/en-US/docs/Web/HTTP/Content_negotiation) > . [PreviousMessage Formats](/api-guidelines/rest-api-guidelines/message/message-formats) [NextHAL](/api-guidelines/rest-api-guidelines/message/hal) Last updated 8 months ago --- # Pagination | API Guidelines A collection resource **SHOULD** provide the [`first`, `last`, `next` and `prev` link](https://tools.ietf.org/html/rfc5988#section-6.2.2) s for navigation within the collection. [](#example) Example ------------------------- The Collection of Orders using the collection navigation link and `offset` and `limit` query parameters: Copy { "_links": { "self": { "href": "/orders?offset=100&limit=10" }, "prev": { "href": "/orders?offset=90&limit=10" }, "next": { "href": "/orders?offset=110&limit=10" }, "first": { "href": "/orders?limit=10" }, "last": { "href": "/orders?offset=900&limit=10" } }, "totalCount": 910, "_embedded": { "order": [\ { ... },\ { ... },\ \ ... \ ] } } [PreviousExecution](/api-guidelines/rest-api-guidelines/execution) [NextLong Running Tasks](/api-guidelines/rest-api-guidelines/execution/long-running-tasks) Last updated 4 years ago --- # Message | API Guidelines This section covers the message format governance. [PreviousStatus Codes](/api-guidelines/rest-api-guidelines/protocol/use-appropriate-status-codes) [NextMessage Formats](/api-guidelines/rest-api-guidelines/message/message-formats) Last updated 6 years ago --- # Long Running Tasks | API Guidelines This section includes the recommended approaches to handling long running tasks (LRTs) in REST APIs. You can identify a LRT quite easily. The main factor to consider are the metrics from latency of the endpoint. If it requiress tens of seconds or even minutes we are facing a problem related to LRTs. LRTs cannot be handled in a regular straight synchronous call. The amount of commited recources at the network, client and server levels are huge when connections are blocked for several minutes. It is strongly recommended to follow a non-blocking solution as it is proposed in this section. [PreviousPagination](/api-guidelines/rest-api-guidelines/execution/pagination) [NextPolling](/api-guidelines/rest-api-guidelines/execution/long-running-tasks/polling) Last updated 9 months ago --- # Application | API Guidelines Every API **SHOULD** use company terms for resource names, relation names and representation message field names. Also, every API **MUST** follow the [naming conventions](/api-guidelines/rest-api-guidelines/evolution/naming-conventions) . [PreviousForeign Key Relations](/api-guidelines/rest-api-guidelines/message/foreign-key-relations) [NextCorporate Data Model](/api-guidelines/rest-api-guidelines/application/harmonize-data) Last updated 6 years ago --- # Corporate Data Model | API Guidelines The design of application data model **MUST** consider the application use cases, as well as the upstream and downstream systems use cases. The design of the data model of an application **MUST** consider the [adidas Corporate Data Model](https://collaboration.adidas-group.com/sites/CS-GDM/Corporate%20Data%20Dictionary/Data%20Dictionary.htm) (internal link). Different names for entities and attributes **MAY** be used **ONLY** if the **CDM** is not including them. If a different name is introduced then it **MUST** be included in the **CDM**. The consistency of the names of entities and attributes across the whole application **MUST** be maintained. [PreviousApplication](/api-guidelines/rest-api-guidelines/application) [NextCommon Data Types](/api-guidelines/rest-api-guidelines/application/common-data-types) Last updated 9 months ago --- # Message Formats | API Guidelines [](#response-message-format) Response Message Format --------------------------------------------------------- All **response** messages **MUST** support an [`application/hal+json`](http://stateless.co/hal_specification.html) (HAL) format. ### [](#error-response-format) Error Response Format The [`application/problem+json`](https://tools.ietf.org/html/rfc7807) (Problem Detail) **MUST** be used to communicate details about an error. [](#request-message-format) Request Message Format ------------------------------------------------------- **Request** messages with body **SHOULD** support an [`application/json`](http://www.json.org) (JSON) format. Where applicable, the request message **SHOULD** also support the [`application/hal+json`](http://stateless.co/hal_specification.html) format. **Request** messages **MAY** also support the [`application/x-www-form-urlencoded`](https://tools.ietf.org/html/rfc1866#section-8.2.1) (URL Encoded) format. [PreviousMessage](/api-guidelines/rest-api-guidelines/message) [NextContent Negotiation](/api-guidelines/rest-api-guidelines/message/content-negotiation) Last updated 8 months ago --- # API First | API Guidelines Everyone **MUST** follow the **API First** principle. The API first principle is an extension of design-first principle. Therefore, a development of an API **MUST** always start with API design without any upfront coding activities. **API design** (e.g., description, schema) **is the master of truth, not the API implementation.** API implementation **MUST** always be compliant to a particular API design which represents the [contract](/api-guidelines/general-guidelines/contract) between API, and it's consumer. [PreviousIntroduction](/api-guidelines/general-guidelines/general-guidelines) [NextContract](/api-guidelines/general-guidelines/contract) Last updated 9 months ago --- # Polling | API Guidelines If an API operation can be considered as a long running task (LRT) and the API Consumer can track its progress, the response to the LRT **MUST** return, in the case of success, the **202 Accepted** status code together with an `application/hal+json` representation of a new **task-tracking resource**. [](#task-tracking-resource) Task Tracking Resource ------------------------------------------------------- The task-tracking resource **SHOULD** convey the information about the status of an asynchronous task. Retrieval of such a resource using the HTTP GET Request Method **SHOULD** be designed as follows: 1. Task is Still Processing Return **200 OK** and representation of the current status. 2. Task Successfully Completed Return **303 See Other** together with [HTTP Location Header](https://tools.ietf.org/html/rfc7231#section-7.1.2) with URI or a outcome resource. 3. Task Failed Return **200 OK** and `application/problem+json` with the problem detail information on the task has failed. [](#design-note) Design Note --------------------------------- The polling (task-tracking) operation requires a clear adaptation on the API Consumer side: * Polling requests frequency depend on the type of operation and specific latency of thre resource. * The identification of the resource has to be correlated along the series of polling requests. The API Consumer has to be able to save this ID and the API Producer has to be able to identify the progress of the operation with that ID. * A security problem can be raised if a non-authorized client retrieves the response for a different resource ID. The authorization data and tasks in progress have to be strongly correlated and controlled to avoid consistency issues. ### [](#example) Example 1. **Initiate the polling task** Copy POST /feeds/tasks/ HTTP/1.1 Content-Type: application/json ... HTTP/1.1 202 Accepted Content-Type: application/hal+json Retry-After: 60 { "_links": { "self": { "href": "/feeds/tasks/1" } }, "message": "Your task to generate feed has been accepted. Try query for result after 60 seconds.", "retryAfter": 60 } 2. **Poll the task status: In progress** Copy GET /feeds/tasks/1 HTTP/1.1 ... HTTP/1.1 200 Ok Content-Type: application/hal+json Retry-After: 30 { "_links": { "self": { "href": "/feeds/tasks/1" } }, "message": "Your feed is being generated. Try query for result after 30 seconds.", "retryAfter": 30 } 3. **Poll the task status: Finished** Copy GET /feeds/tasks/1 HTTP/1.1 ... HTTP/1.1 303 See Other Location: /feeds/1 Content-Location: /feeds/tasks/1 Content-Type: application/hal+json { "_links": { "self": { "href": "/feeds/tasks/1" }, "feed": { "href": "/feeds/1" } }, "message": "Your feed is ready." } 4. **Poll the task status: Failure** Copy GET /feeds/tasks/1 HTTP/1.1 ... HTTP/1.1 200 OK Content-Type: application/problem+json { "title": "Wrong input parameters", "detail: "Missing required input parameter XYZ.", "status": 400 } [PreviousLong Running Tasks](/api-guidelines/rest-api-guidelines/execution/long-running-tasks) [NextCallback](/api-guidelines/rest-api-guidelines/execution/long-running-tasks/callback) Last updated 9 months ago --- # Core REST Principles | API Guidelines This section outlines the foundation upon which the REST API Guidelines are built. [PreviousIntroduction](/api-guidelines/rest-api-guidelines/rest) [NextOpenAPI Specification](/api-guidelines/rest-api-guidelines/core-principles/openapi-specification) Last updated 9 months ago --- # Common Data Types | API Guidelines [](#date-and-time-format) Date and Time Format --------------------------------------------------- Date and Time **MUST** always conform to the [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format e.g.: `2017-06-21T14:07:17Z` (date time) or `2017-06-21` (date), it **MUST** use the UTC (without time offsets). [](#duration-format) Duration Format ----------------------------------------- Duration format **MUST** conform to the [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) standard e.g.: `P3Y6M4DT12H30M5S` (three years, six months, four days, twelve hours, thirty minutes, and five seconds). [](#time-interval-format) Time Interval Format --------------------------------------------------- Time Interval format **MUST** conform to the [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) standard e.g.: `2007-03-01T13:00:00Z/2008-05-11T15:30:00Z`. [](#standard-time-stamps) Standard Time Stamps --------------------------------------------------- Where applicable, a resource representation **SHOULD** contain the standard timestamps: * `createdAt` * `updatedAt` * `finishedAt` ### [](#example) Example Copy { "createdAt": "2017-01-01T12:00:00Z", "updatedAt": "2017-01-01T13:00:00Z", ... } [](#language-code-format) Language Code Format --------------------------------------------------- Language codes **MUST** conform to the [ISO 639](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) e.g.: `en` for English. [](#country-code-format) Country Code Format ------------------------------------------------- Country codes **MUST** conform to the [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) e.g.: `DE` for Germany. [](#currency-format) Currency Format ----------------------------------------- Currency codes **MUST** conform to the [ISO 4217](https://en.wikipedia.org/wiki/ISO_4217) e.g.: `EUR` for Euro. [PreviousCorporate Data Model](/api-guidelines/rest-api-guidelines/application/harmonize-data) [NextExecution](/api-guidelines/rest-api-guidelines/execution) Last updated 6 years ago --- # Security | API Guidelines Every registered API **MUST** be assigned a unique Client ID and a Client Secret as a part of an HTTP header. The Client Secret **MUST NOT** be shared. **DO NOT** solely rely on a Client ID for authentication. [](#access-control) Access Control --------------------------------------- Not every user has a right to every web service. This is vital, as you don't want administrative web services to be misused. The API key **SHOULD** be sent along as a cookie, body parameter, or HTTP message header to ensure that privileged collections or actions are properly protected from unauthorized use. Every API **MUST BE** authenticated before it can be used. [](#masking-http-headers) Masking HTTP Headers --------------------------------------------------- Server versioning information or any other sensitive information from the HTTP headers **SHOULD BE** removed/masked according to industry best practices. This prevents any form of targeted attacks since the vulnerabilities are mostly specific to the vendors. [](#use-security-http-headers) Use Security HTTP Headers ------------------------------------------------------------- Modern browsers support many HTTP headers that can improve web application security to protect against clickjacking, cross-site scripting, and other common attacks. Your API **SHOULD** use security HTTP headers to improve the level of protection. See the [list of OWASP Secure Headers](https://owasp.org/www-project-secure-headers/) to form the combination of headers. Ideally you **SHOULD** inlcude HTTP Security Headers at least in these areas unless there is an incompatibility with some functional requirement: * HTTP Strict Transport Security * Content-Security-Policy * X-Frame-Options * X-Content-Type-Options * X-Permitted-Cross-Domain-Policies * Referrer-Policy * Clear-Site-Data * Cross-Origin-Embedder-Policy * Cross-Origin-Opener-Policy * Cross-Origin-Resource-Policy [](#session-management) Session Management ----------------------------------------------- RESTful web services **SHOULD** use session-based authentication, either by establishing a session token via a POST or by using an API key (Client ID and a Client Secret) as a POST body argument or as a cookie. Usernames, passwords, session tokens, API keys, and sensitive information **MUST NOT** appear in the URL, as this can be captured in web server logs, which makes them intrinsically valuable. [](#protect-http-methods) Protect HTTP Methods --------------------------------------------------- RESTful API often use GET (read), POST (create), PUT (replace/update) and DELETE (to delete a record). Not all of these are valid choices for every single resource collection, user, or action. Make sure the incoming HTTP method is valid for the session token/API key and associated resource collection, action, and record. [](#http-status-codes) HTTP Status Codes --------------------------------------------- While designing a REST API, **DO NOT** just use 200 for success or 404 for error. Every error message needs to be customized as NOT to reveal any unnecessary information. Here are some guidelines to consider for each REST API status return code. Proper error handle may help to validate the incoming requests and better identify the potential security risks. * 200 OK - Response to a successful REST API action. * 400 Bad Request - The request is malformed, such as message body format error. * 401 Unauthorized - Wrong or no authentication ID/password provided. * 403 Forbidden - It's used when the authentication succeeded but authenticated user doesn't have permission to the requested resource * 404 Not Found - When a non-existent resource is requested * 405 Method Not Allowed - The error checking for unexpected HTTP method. For example, the RestAPI is expecting HTTP GET, but HTTP PUT is used. * 429 Too Many Requests - The error is used when there may be DOS attack detected or the request is rejected due to rate limiting [](#input-validation) Input Validation ------------------------------------------- Everything you know about [input validation](https://www.owasp.org/index.php/Data_Validation) applies to RESTful web services, but add 10% because automated tools can easily fuzz your interfaces for hours on end at high velocity. Help the user input high-quality data into your web services, such as ensuring a Zip code makes sense for the supplied address, or the date makes sense. If not, reject that input. Also, make sure that the output encoding is robust for your application. Some other specific forms of input validations need to be implemented: * Secure parsing: Use a secure parser for parsing the incoming messages. If you are using XML, make sure to use a parser that is NOT VULNERABLE to XXE and similar attacks. * Strong typing: It's difficult to perform most attacks if the only allowed values are true or false, or a number, or one of a small number of acceptable values. Strongly type incoming data as quickly as possible. * Validate incoming content-types: When POSTing or PUTting new data, the client will specify the Content-Type (e.g. application/xml or application/json) of the incoming data. The server **SHOULD NEVER** assume the Content-Type; it **SHOULD ALWAYS** check that the Content-Type header and the content are the same types. A lack of Content-Type header or an unexpected Content-Type header **SHOULD** result in the server rejecting the content with a 406 Not Acceptable response. * Validate response types: It is common for REST services to allow multiple response types (e.g. application/xml or application/json, and the client specifies the preferred order of response types by the Accept header in the request. **DO NOT** simply copy the Accept header to the Content-type header of the response. Reject the request (ideally with a 406 Not Acceptable response) if the Accept header does not specifically contain one of the allowable types. Because there are many MIME types for the typical response types, it's important to document for clients specifically which MIME types should be used. * XML input validation: XML-based services **MUST** ensure that they are protected against common XML-based attacks by using secure XML-parsing. This typically means protecting against XML External Entity attacks, XML-signature wrapping etc. [](#escape-content) Escape Content --------------------------------------- This means removing any executable code that would cause the browser to do something you don’t want it to. Typically this means removing `// <![CDATA[` tags and HTML attributes that cause JavaScript to be evaluated. If you use standard data formats like JSON, you can use standard libraries which have been thoroughly checked by many professionals. However, **DO NOT TRY TO DO THIS YOURSELF**. Use a known library or the auto-escaping features of your favorite template library. This needs to be done in the browser and on your server if you allow users to submit data that is saved into a database.\ \ [](#restrict-testing-environment)\ \ Restrict Testing Environment\ \ \ -------------------------------------------------------------------\ \ THUMB Rule: Production data or any form of sensitive data **SHOULD NOT** be used while testing the APIs in the test environment.\ \ [](#storing-tokens-at-client-side)\ \ Storing Tokens at Client Side\ \ \ ---------------------------------------------------------------------\ \ There are two ways to save authentication information in the browser:\ \ * Cookies\ \ * HTML5 Web Storage\ \ \ In each case, you have to trust that browsers are implemented correctly and that Website A can't somehow access the authentication information for Website B. In that sense, both storage mechanisms are equally secure. Problems can arise regarding how you use them though.\ \ * If you use cookies: The browser will automatically send the authentication information with every request to the API. This can be convenient so long as you know it's happening. Prevention against Cross Site Request Forgery (CSRF) is a must while using this technique. It is also strongly recommended to use cookies with HTTPOnly and Secure flags set. This will allow the browser to send along the token for authentication purposes, but won’t expose it to the JavaScript environment.\ \ * If you use HTML5 Web Storage: You have to write JavaScript that manages exactly when and what authentication information is sent.\ \ \ [](#protect-against-cross-site-request-forgery)\ \ Protect against Cross-Site Request Forgery\ \ \ -----------------------------------------------------------------------------------------------\ \ For resources exposed by RESTful web services, it's important to make sure any PUT, POST, and DELETE request is protected from Cross Site Request Forgery. Typically, one would use a token-based approach. See [Cross-Site Request Forgery Prevention Cheat Sheet](https://www.owasp.org/index.php/Cross-Site_Request_Forgery_%28CSRF%29_Prevention_Cheat_Sheet)\ for more information on how to implement CSRF-protection.\ \ CSRF is easily achieved even when using random tokens if any XSS exists within your application, so **PLEASE MAKE SURE** you understand [how to prevent XSS](https://www.owasp.org/index.php/XSS_%28Cross_Site_Scripting%29_Prevention_Cheat_Sheet)\ .\ \ [](#insecure-direct-object-references)\ \ Insecure direct object references\ \ \ -----------------------------------------------------------------------------\ \ A URL or even a POSTed form **SHOULD NEVER** contain an access control "key" or similar that provides automatic verification. A contextual data check needs to be done, server side, with each request.\ \ [](#enable-cors-for-all-apis)\ \ Enable CORS for all APIs\ \ \ -----------------------------------------------------------\ \ When your API's resources receive requests from a domain other than the API's domain, you **MUST** enable cross-origin resource sharing (CORS) for selected methods on the resource. This amounts to having your API respond to the OPTIONS preflight request with at least the following CORS-required response headers:\ \ * Access-Control-Allow-Methods\ \ * Access-Control-Allow-Headers\ \ * Access-Control-Allow-Origin\ \ \ [](#data-in-transit)\ \ Data in transit\ \ \ -----------------------------------------\ \ Unless the public information is entirely read-only, the use of TLS v1.2 should be **MANDATED**, especially when credentials, updates, deletions, and any value transactions are performed. The overhead of TLS is negligible on modern hardware, with a minor latency increase that is more than compensated by safety for the end user.\ \ [](#message-integrity)\ \ Message Integrity\ \ \ ---------------------------------------------\ \ In addition to HTTPS/TLS, JSON Web Token (JWT) is an open standard that defines a compact and self-contained way for securely transmitting information between parties as a JSON object. JWT can be used not only to ensure the message integrity but also authentication of both message sender/receiver. The JWT includes the digital signature hash value of the message body to ensure message integrity during the transmission.\ \ [](#weak-ssl-tls-ciphers-support)\ \ Weak SSL/TLS Ciphers Support:\ \ \ --------------------------------------------------------------------\ \ The encryption ciphers supported by the server may allow an attacker to eavesdrop on the connection. Verify the following guidelines:\ \ * When serving up content to your users, **ONLY** strong ciphers are enabled (128 bits and above).\ \ * When connecting to other remote systems ensure that your client **DOES NOT** connect using a weak cipher if the server supports it.\ \ * Renegotiation **MUST** be properly configured (e.g. Insecure Renegotiation **MUST** be disabled, due to Man in the Middle (MiTM) attacks and Client-initiated Renegotiation **MUST** be disabled, due to Denial of Service vulnerability).\ \ * MD5 **MUST NOT** be used, due to known collision attacks.\ \ * RC4 **MUST NOT** be used, due to cryptoanalytical attacks\ \ * Server **SHOULD** be protected from BEAST Attack\ \ * Server **SHOULD** be protected from CRIME attack, TLS compression **MUST** be disabled\ \ * Server **SHOULD** support Forward Secrecy\ \ \ [](#mixed-content)\ \ Mixed Content\ \ \ -------------------------------------\ \ When serving up content to your users over SSL, it’s important that you **DO NOT** include content served over HTTP such as Images, JavaScript, Flash, or CSS. By mixing HTTP content with HTTPS content, you expose your users to Man-in-the-Middle attacks and eliminate the security benefits that SSL/TLS provides.\ \ [](#ssl-certificate-validity-client-and-server)\ \ SSL Certificate Validity – client and server\ \ \ -------------------------------------------------------------------------------------------------\ \ For the communication to be set up, a number of checks on the certificates **MUST** be passed:\ \ * Checking if the Certificate Authority (CA) is a known one (meaning one considered trusted);\ \ * Checking that the certificate is currently valid;\ \ * Checking that the name of the site and the name reported in the certificate match.\ \ \ [](#certificate-requirements)\ \ Certificate Requirements\ \ \ -----------------------------------------------------------\ \ The following checklist **MUST** be followed while using an SSL certificate:\ \ * X.509 certificates key length **MUST** be strong (e.g. if RSA or DSA is used the key MUST be at least 1024 bits).\ \ * X.509 certificates **MUST** be signed only with secure hashing algorithms (e.g. not signed using the MD5 hash, due to known collision attacks on this hash).\ \ * Fully Qualified Domain Name (FQDN) certificates is a **MANDATE**. This is a certificate that has been issued with a name registered with an entity that manages a top-level domain (TLD). The differentiating characteristic about an FQDN is that it is unique. There is one controller and that controller determines who can have any name under that root.\ \ * **NO USAGE** of Wildcard SSL Certificate.\ \ * SHA-1 (or MD5) certificates **SHOULD NOT BE** used. The problem isn't the security of the server's real certificate; it's the client policy that allows the client to trust low-security certificates.\ \ \ [](#penetration-testing)\ \ Penetration Testing\ \ \ -------------------------------------------------\ \ An exhaustive penetration testing **MUST** be performed against all the developed APIs exposed to the public internet and within adidas internal network. For detailed understanding of the process, please contact the adidas Global IT Security Team.\ \ [PreviousJSON](/api-guidelines/general-guidelines/json)\ [NextTooling](/api-guidelines/general-guidelines/n_tooling)\ \ Last updated 9 months ago --- # Design Maturity | API Guidelines [](#api-design-maturity) API Design Maturity ------------------------------------------------- > How to design an API Every API design **MUST** be **resource-centric** ([Web API Design Maturity Model Level 2](http://amundsen.com/talks/2016-11-apistrat-wadm/2016-11-apistrat-wadm.pdf) ). That is an API design **MUST** revolve around Web-styled _resources_, _relations_ between the resources and the _actions_ the resources may afford. An API design **MAY** be **affordance-centric** ([Web API Design Maturity Model Level 3](http://amundsen.com/talks/2016-11-apistrat-wadm/2016-11-apistrat-wadm.pdf) ). [](#api-design-implementation-maturity) API Design Implementation Maturity ------------------------------------------------------------------------------- > How to implement the API design Every API design implementation using the HTTP protocol **MUST** use the appropriate **HTTP Request Method** ([Richardson Maturity Model Level 2](https://martinfowler.com/articles/richardsonMaturityModel.html#level2) ) to implement an action afforded by a resource. An API design implementation **SHOULD** include **hypermedia controls** (HATEOAS) ([Richardson Maturity Model Level 3](https://martinfowler.com/articles/richardsonMaturityModel.html#level3) ). [PreviousAPI Design Platform](/api-guidelines/rest-api-guidelines/core-principles/design-platform) [NextTesting](/api-guidelines/rest-api-guidelines/core-principles/testing) Last updated 6 years ago --- # Batch Operations | API Guidelines [](#processing-similar-resources) Processing Similar Resources ------------------------------------------------------------------- An operation that needs to process several related resources in bulk **SHOULD** uses a collection resource with the appropriate HTTP Request Method. When processing existing resource the request message body **MUST** contain the URLs of the respective resources being processed. ### [](#example) Example #### [](#create-multiple-orders-at-once) Create Multiple Orders at Once Copy POST /orders Content-Type: application/json { "order": [\ {\ "itemCount": 42\ },\ {\ "itemCount": 2\ }\ ] } #### [](#update-multiple-orders-at-once) Update Multiple Orders at Once > NOTE: The self-link relation identifies the existing resource being edited. Copy PATCH /orders Content-Type: application/json { "order": [\ {\ "_links": {\ "self": { "href": "/order/1"}\ },\ "itemCount": 42\ },\ {\ "_links": {\ "self": { "href": "/order/2"}\ }, \ "itemCount": 2\ }\ ] } [](#results-of-bulk-operation) Results of Bulk Operation ------------------------------------------------------------- Every bulk operation **MUST** be atomic and treated as any other operation. > _The server must implement bulk requests as atomic. If the request is for creating ten addresses, the server should create all ten addresses before returning a successful response code. The server should not commit changes partially in the case of failures._ [](#do-not-use-post-tunneling) DO NOT USE "POST Tunneling." ---------------------------------------------------------------- Every API **MUST** avoid tunneling multiple HTTP Request using one POST request. Instead, provide an application-specific resource to process the batch request. [](#non-atomic-bulk-operations) Non-atomic Bulk Operations --------------------------------------------------------------- Non-atomic bulk operations are **strongly discouraged** as they bring additional burden and confusion to the client and are difficult to consume, debug, maintain and evolve over the time. The suggestion is to **split** a non-atomic operation into several atomic operations. The cost of few more calls will be greatly outweighed but the cleaner design, clarity and easier maintainability. However, in such an operation has to be provided such a non-atomic bulk operation **MUST** conform to the following guidelines. 1. Non-atomic bulk operation **MUST** return a success status code (e.g. **200 OK**) only if every and all sub-operation succeeded. 2. If any single one sub-operation fails the whole non-atomic bulk operation **MUST** return the respective **4xx** or **5xx** status code. 3. In the case of a failure the response **MUST** contain the [problem detail](/api-guidelines/rest-api-guidelines/message/message-formats#error-response-format) information about every sub-operation that has failed. 4. **The client MUST be aware that the operation is non-atomic and that even the operation might have failed some sub-operations were processed successfully.** ### [](#example-1) Example Non-atomic request for creating four orders: Copy POST /orders Content-Type: application/json { "order": [\ {\ "itemCount": 42\ },\ {\ "itemCount": -100\ }, \ {\ "itemCount": 42\ },\ {\ "itemCount": 1.3232\ }\ ] } And the error response: Copy HTTP/1.1 400 Bad Request Content-Type: application/problem+json { "type": "https://example.net/partial_operation_failure", "title": "Partial Failure", "detail": "Some orders couldn't be created, other orders were created.", "errors": [\ {\ "type": "https://example.net/invalid-params",\ "instance": "/orders/1",\ "title": "Invalid Parameter",\ "detail": "itemCount must be a positive integer",\ "status": 400\ },\ {\ "type": "https://example.net/invalid-params",\ "instance": "/orders/3",\ "title": "Invalid Parameter",\ "detail": "itemCount must be a positive integer",\ "status": 400\ }\ ], "processed": ... } The `processed` field should contain the result of processed sub-operations as if they were returned in a 200 OK. [PreviousFiles Upload](/api-guidelines/rest-api-guidelines/execution/long-running-tasks/files-upload) [NextSearch Requests](/api-guidelines/rest-api-guidelines/execution/search-requests) Last updated 9 months ago --- # Problem Detail | API Guidelines The [`application/problem+json`](https://tools.ietf.org/html/rfc7807) (Problem Detail) **MUST** be used to communicate details about an error. Problem Detail is intended for use with the HTTP status codes 4xx and 5xx. Problem Detail **MUST NOT** be used with 2xx status code responses. At the minimum, any Problem Detail response **MUST** have the `title` and `detail` fields. `title` value **SHOULD NOT** change from occurrence to occurence of the problem, except for purposes of localization (e.g., using proactive content negotiation) [read more](https://tools.ietf.org/html/rfc7807#section-3.1) ### [](#example) Example Copy { "title": "Authentication required", "detail": "Missing authentication credentials for the Greeting resource." } > NOTE: `title` and `detail` fields **SHOULD NOT** be parsed to determine the nature of the error. Instead `type` **MUST** be used. [](#optional-fields) Optional Fields ----------------------------------------- It **SHOULD** have the `type` field with the identifier of the error, besides it **MAY** have the `instance` field with the URI of the resource in question. If the Problem Detail response has the `status` field it **MUST** have the same value as HTTP Status code from of the response. Copy { "type": "https://adidas-group.com/problems/scv/unauthorized", "title": "Authentication required", "detail": "Missing authentication credentials for the Greeting resource.", "instance": "/greeting", "status": 401 } > NOTE: The `type` field is an identifier, and as such it **MAY** be used to denote additional error codes. Keep in mind that the identifier should be a URI. [](#additional-fields) Additional Fields --------------------------------------------- If needed, the Problem Detail **MAY** include additional fields, refer to [RFC7807](https://tools.ietf.org/html/rfc7807) for details. [](#validation-errors) Validation Errors --------------------------------------------- When necessary, a Problem Detail response **MAY** include additional error details about the problems that have occurred. These additional errors **MUST** be under the `errors` collection and **MUST** follow the Problem Detail structure. ### [](#example-1) Example Request: Copy POST /my-resource HTTP/1.1 Content-Type: application/json { "age": -32, "color": "cyan" } Response: Copy HTTP/1.1 400 Bad Request Content-Type: application/problem+json Content-Language: en { "type": "https://example.net/validation_error", "title": "Your request parameters didn't validate.", "instance": "/my-resource", "status": 400, "errors": [\ {\ "type": "https://example.net/invalid_params",\ "instance": "/age",\ "title": "Invalid Parameter",\ "detail": "age must be a positive integer"\ },\ {\ "type": "https://example.net/invalid_params",\ "instance": "/color",\ "title": "Invalid Parameter",\ "detail": "color must be 'green', 'red' or 'blue'"\ }\ ] } [](#problem-detail-and-content-negotiation) Problem Detail and Content Negotiation --------------------------------------------------------------------------------------- ### [](#example-2) Example A request is made to retrieve a resource representation: Copy GET /greeting HTTP/1.1 Accept: application/hal+json However, in order to make this request, the client needs to be authorized. Since the request is made without the authorization credentials the **401 Unauthorized** response is returned together with details using the `application/problem+json` media type: Copy HTTP/1.1 401 Unauthorized Content-Type: application/problem+json Content-Language: en { "type": "https://adidas-group.com/problems/scv/unauthorized", "title": "Authentication required", "detail": "Missing authentication credentials for the Greeting resource.", "instance": "/greeting", "status": 401 } [](#no-stack-traces-or-server-logs) No Stack Traces or Server Logs ----------------------------------------------------------------------- > _Problem details are not a debugging tool for the underlying implementation; rather, they are a way to expose greater detail about the HTTP interface itself._ > > _–_ [_RFC7807_](https://tools.ietf.org/html/rfc7807) A Problem Detail response **MUST NOT** contain a program stack trace or server log for debugging purposes. Instead, provide a `logref` field with reference to the particular server log. [](#working-with-problem-detail) Working with Problem Detail ----------------------------------------------------------------- An API description **MAY** list all the error codes with which the API responds. The error responses **SHOULD** describre the error object model schema. It is **RECOMMENDED** to include examples of a possible error response. The error description and/or error example **MAY** list all the types of errors returned for a given error code. [](#external-resources) External resources ----------------------------------------------- There are a whole plethora of libraries working with Problem Detail, for example, see [Zalando / Problem](https://github.com/zalando/problem) (Java). [PreviousHAL](/api-guidelines/rest-api-guidelines/message/hal) [NextForeign Key Relations](/api-guidelines/rest-api-guidelines/message/foreign-key-relations) Last updated 9 months ago ---