Zalando RESTful API and Event Guidelines
GitHub Repository as part of Zalando SE Opensource
- Zalando RESTful API and Event Guidelines
- 1. Introduction
- 2. Principles
- 3. Basic Terminology
- 4. General guidelines
- 5. REST Basics - Meta information
- 6. REST Basics - Security
- 7. REST Basics - Data formats
- MUST use standard data formats
- MUST define a format for number and integer types
- MUST use standard formats for date and time properties
- SHOULD use appropriate formats for date and time properties
- SHOULD use standard formats for time duration and interval properties
- MUST use standard formats for country, language and currency properties
- SHOULD use content negotiation, if clients may choose from different resource representations
- SHOULD only use UUIDs if necessary
- 8. REST Basics - URLs
- SHOULD not use /api as base path
- MUST pluralize resource names
- MUST use URL-friendly resource identifiers
- MUST use kebab-case for path segments
- MUST use normalized paths without empty path segments and trailing slashes
- MUST keep URLs verb-free
- MUST avoid actions — think about resources
- SHOULD define useful resources
- MUST use domain-specific resource names
- SHOULD model complete business processes
- MUST identify resources and sub-resources via path segments
- MAY expose compound keys as resource identifiers
- MAY consider using (non-) nested URLs
- SHOULD limit number of resource types
- SHOULD limit number of sub-resource levels
- MUST use snake_case (never camelCase) for query parameters
- MUST stick to conventional query parameters
- 9. REST Basics - JSON payload
- MUST use JSON as payload data interchange format
- SHOULD design single resource schema for reading and writing
- SHOULD be aware of services not fully supporting JSON/unicode
- MAY pass non-JSON media types using data specific standard formats
- SHOULD use standard media types
- SHOULD pluralize array names
- MUST property names must be snake_case (and never camelCase)
- SHOULD declare enum values using UPPER_SNAKE_CASE string
- SHOULD use naming convention for date/time properties
- SHOULD define maps using
additionalProperties - MUST use same semantics for
nulland absent properties - MUST not use
nullfor boolean properties - SHOULD not use
nullfor empty arrays - MUST use common field names and semantics
- MUST use the common address fields
- MUST use the common money object
- 10. REST Basics - HTTP requests
- MUST use HTTP methods correctly
- MUST fulfill common method properties
- SHOULD consider to design
POSTandPATCHidempotent - SHOULD use secondary key for idempotent
POSTdesign - MAY support asynchronous request processing
- MUST define collection format of header and query parameters
- SHOULD design simple query languages using query parameters
- SHOULD design complex query languages using JSON
- MUST document implicit response filtering
- 11. REST Basics - HTTP status codes
- MUST use official HTTP status codes
- MUST specify success and error responses
- MUST preserve end-to-end semantics of HTTP status codes
- SHOULD be careful with interpreting 404 status code
- SHOULD only use most common HTTP status codes
- MUST use most specific HTTP status codes
- MUST use code 207 for batch or bulk requests
- MUST use code 429 with headers for rate limits
- MUST support problem JSON
- MUST not expose stack traces
- SHOULD not use redirection codes
- 12. REST Basics - HTTP headers
- Using Standard Header definitions
- MAY use standard headers
- SHOULD use kebab-case with uppercase separate words for HTTP headers
- MUST use
Content-*headers correctly - SHOULD use
Locationheader instead ofContent-Locationheader - MAY use
Content-Locationheader - MAY consider to support
Preferheader to handle processing preferences - MAY consider to support
ETagtogether withIf-Match/If-None-Matchheader - MAY consider to support
Idempotency-Keyheader - SHOULD use only the specified proprietary Zalando headers
- MUST propagate proprietary headers
- MUST support
X-Flow-ID
- 13. REST Design - Hypermedia
- MUST use REST maturity level 2
- MAY use REST maturity level 3 - HATEOAS
- MUST use common hypertext controls
- SHOULD use simple hypertext controls for pagination and self-references
- MUST use full, absolute URI for resource identification (with same host, if applicable)
- MUST not use link headers with JSON entities
- 14. REST Design - Performance
- 15. REST Design - Pagination
- 16. REST Design - Compatibility
- MUST not break backward compatibility
- SHOULD prefer compatible extensions
- SHOULD design APIs conservatively
- MUST prepare clients to accept compatible API extensions
- MUST treat OpenAPI specification as open for extension by default
- SHOULD avoid versioning
- MUST use media type versioning
- MUST not use URL versioning
- MUST always return JSON objects as top-level data structures
- SHOULD use open-ended list of values (via
examples) for enumeration types
- 17. REST Design - Deprecation
- MUST reflect deprecation in API specifications
- MUST obtain approval of clients before API shut down
- MUST collect external partner consent on deprecation time span
- MUST monitor usage of deprecated API scheduled for sunset
- SHOULD add
DeprecationandSunsetheader to responses - SHOULD add monitoring for
DeprecationandSunsetheader - MUST not start using deprecated APIs
- 18. REST Operation
- 19. EVENT Basics - Event Types
- MUST define events compliant with overall API guidelines
- MUST treat events as part of the service interface
- MUST make event schema available for review
- MUST specify and register events as event types
- MUST follow naming convention for event type names
- MUST indicate ownership of event types
- MUST carefully define the compatibility mode
- MUST ensure event schema conforms to OpenAPI schema object
- SHOULD avoid
additionalPropertiesin event type schemas - MUST use semantic versioning of event type schemas
- 20. EVENT Basics - Event Categories
- MUST ensure that events conform to an event category
- MUST provide mandatory event metadata
- MUST provide unique event identifiers
- MUST use general events to signal steps in business processes
- SHOULD provide explicit event ordering for general events
- MUST use data change events to signal mutations
- MUST provide explicit event ordering for data change events
- SHOULD use the hash partition strategy for data change events
- 21. EVENT Design
- SHOULD avoid writing sensitive data to events
- MUST be robust against duplicates when consuming events
- SHOULD design for idempotent out-of-order processing
- MUST ensure that events define useful business resources
- SHOULD ensure that data change events match the APIs resources
- MUST maintain backwards compatibility for events
- Appendix A: References
- Appendix B: Tooling
- Appendix C: Best practices
- Appendix D: Changelog
1. Introduction
Zalando’s software architecture centers around decoupled microservices that provide functionality via RESTful APIs with a JSON payload. Small engineering teams own, deploy and operate these microservices in their AWS (team) accounts. Our APIs express most purely what our systems do, and are therefore highly valuable business assets. Designing high-quality, long-lasting APIs has become even more critical for us since we started developing our new open platform strategy, which transforms Zalando from an online shop into an expansive fashion platform. Our strategy emphasizes developing lots of public APIs for our external business partners to use via third-party applications.
With this in mind, we’ve adopted "API First" as one of our key engineering principles. Microservices development begins with API specification outside the code and ideally involves ample peer-review feedback to achieve high-quality APIs. API First encompasses a set of quality-related standards and fosters a peer review culture including a lightweight review procedure. We encourage our teams to follow them to ensure that our APIs:
-
are easy to understand and learn
-
are general and abstracted from specific implementation and use cases
-
are robust and easy to use
-
have a common look and feel
-
follow a consistent RESTful style and syntax
-
are consistent with other teams’ APIs and our global architecture
Ideally, all Zalando APIs will look like the same author created them.
Conventions used in these guidelines
The requirement level keywords "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" used in this document (case insensitive) are to be interpreted as described in RFC 2119.
Zalando specific information
The purpose of our "RESTful API guidelines" is to define standards to successfully establish "consistent API look and feel" quality. The API Guild (internal_link) drafted and owns this document. Teams are responsible to fulfill these guidelines during API development and are encouraged to contribute to guideline evolution via pull requests.
These guidelines will, to some extent, remain work in progress as our work evolves, but teams can confidently follow and trust them.
In case guidelines are changing, following rules apply:
-
existing APIs don’t have to be changed, but we recommend it
-
clients of existing APIs have to cope with these APIs based on outdated rules
-
new APIs have to respect the current guidelines
Furthermore you should keep in mind that once an API becomes public externally available, it has to be re-reviewed and changed according to current guidelines - for sake of overall consistency.
2. Principles
API design principles
Comparing SOA web service interfacing style of SOAP vs. REST, the former tend to be centered around operations that are usually use-case specific and specialized. In contrast, REST is centered around business (data) entities exposed as resources that are identified via URIs and can be manipulated via standardized CRUD-like methods using different representations, and hypermedia. RESTful APIs tend to be less use-case specific and come with less rigid client / server coupling and are more suitable for an ecosystem of (core) services providing a platform of APIs to build diverse new business services. We apply the RESTful web service principles to all kind of application (micro-) service components, independently from whether they provide functionality via the internet or intranet.
-
We prefer REST-based APIs with JSON payloads
-
We prefer systems to be truly RESTful [1]
An important principle for API design and usage is Postel’s Law, aka The Robustness Principle (see also RFC 1122):
-
Be liberal in what you accept, be conservative in what you send
Readings: Some interesting reads on the RESTful API design style and service architecture:
API as a product
As mentioned above, Zalando is transforming from an online shop into an expansive fashion platform comprising a rich set of products following a Software as a Platform (SaaP) model for our business partners. As a company we want to deliver products to our (internal and external) customers which can be consumed like a service.
Platform products provide their functionality via (public) APIs; hence, the design of our APIs should be based on the API as a Product principle:
-
Treat your API as product and act like a product owner
-
Put yourself into the place of your customers; be an advocate for their needs
-
Emphasize simplicity, comprehensibility, and usability of APIs to make them irresistible for client engineers
-
Actively improve and maintain API consistency over the long term
-
Make use of customer feedback and provide service level support
Embracing 'API as a Product' facilitates a service ecosystem, which can be evolved more easily and used to experiment quickly with new business ideas by recombining core capabilities. It makes the difference between agile, innovative product service business built on a platform of APIs and ordinary enterprise integration business where APIs are provided as "appendix" of existing products to support system integration and optimised for local server-side realization.
Understand the concrete use cases of your customers and carefully check the trade-offs of your API design variants with a product mindset. Avoid short-term implementation optimizations at the expense of unnecessary client side obligations, and have a high attention on API quality and client developer experience.
API as a Product is closely related to our API First principle (see next chapter) which is more focused on how we engineer high quality APIs.
API first
API First is one of our engineering and architecture principles. In a nutshell API First requires two aspects:
-
define APIs first, before coding its implementation, using a standard specification language
-
get early review feedback from peers and client developers
By defining APIs outside the code, we want to facilitate early review feedback and also a development discipline that focus service interface design on…
-
profound understanding of the domain and required functionality
-
generalized business entities / resources, i.e. avoidance of use case specific APIs
-
clear separation of WHAT vs. HOW concerns, i.e. abstraction from implementation aspects — APIs should be stable even if we replace complete service implementation including its underlying technology stack
Moreover, API specifications using a standard format facilitate…
-
single source of truth for the API specification; it is a crucial part of a contract between service provider and client users
-
infrastructure tooling for API discovery, API GUIs, API documents, automated quality checks
Elements of API First are also this API Guidelines and a standardized API review process as to get early review feedback from peers and client developers. Peer review is important for us to get high quality APIs, to enable architectural and design alignment and to supported development of client applications decoupled from service provider engineering life cycle.
It is important to learn, that API First is not in conflict with the agile development principles that we love. Service applications should evolve incrementally — and so its APIs. Of course, our API specification will and should evolve iteratively in different cycles; however, each starting with draft status and early team and peer review feedback. API may change and profit from implementation concerns and automated testing feedback. API evolution during development life cycle may include breaking changes for not yet productive features and as long as we have aligned the changes with the clients. Hence, API First does not mean that you must have 100% domain and requirement understanding and can never produce code before you have defined the complete API and get it confirmed by peer review.
On the other hand, API First obviously is in conflict with the bad practice of publishing API specifications and asking for peer review after the service integration or even the service productive operation has started. It is crucial to request and get early feedback — as early as possible, but not before the API changes are comprehensive with focus to the next evolution step and have a certain quality (including API Guideline compliance), already confirmed via team internal reviews.
3. Basic Terminology
In the context of our REST API Guidelines, we differentiate the following entity types:
-
OpenAPI Specification (OAS) — the REST API specification format defined as standard by the OpenAPI Initiative. We currently encourage using OpenAPI 3.1 version for API specifications.
-
API Specification (aka OpenAPI Description (OAD) — the document in OAS format specifying an API, its syntax and semantics. It should provide all information for clients to use the API, and serves as the interface definition of the API implementation.
-
API — the REST API interface provided via "the wire" (HTTP+TCP/IP) by a concrete service that is deployed and running.
-
API Implementation — the implementation of the API as part of a concrete service implementation. It is typically code written in a programming language like Java or Python, and there can be multiple concrete implementations for the same API.
The API Specification, of course, might differ from the actual API provided by a concrete service, because e.g. the service implementation is incomplete, not up-to-date or faulty. The API Specification that is intended to be implemented by the service must / should be published with the service deployment.
Note, OpenAPI allows API Specifications being composed of an entry document and URL-referenced OpenAPI Documents defining path, component or webhook elements. However, we require to provide the API specification using a single self-contained YAML document for better readability and consistent versioning and life-cycle handling — see MUST provide API Specifications using OpenAPI.
4. General guidelines
The titles are marked with the corresponding labels: MUST, SHOULD, MAY.
MUST follow API first principle
You must follow the API First Principle, more specifically:
-
You must define APIs first, before coding its implementation, using OpenAPI as specification language
-
You must design your APIs consistently with these guidelines; use our API Linter Service (internal_link) for automated rule checks.
-
You must call for early review feedback from peers and client developers, and apply our lightweight API review process (internal_link) for all component external APIs, i.e. all apis with
x-api-audience =/= component-internal(see MUST provide API audience).
MUST provide API Specifications using OpenAPI
We use the standard provided by the OpenAPI Initiative to define API specifications. API designers are required to provide the API specification using a single self-contained YAML file for better readability. We encourage using OpenAPI 3.1 version, especially for new APIs. The API specification documents should be subject to version control using a source code management system, and you MUST publish OpenAPI specification for APIs.
Hint: Our API infrastructure does not break, but might not yet fully support
all OpenAPI 3.1 changes (e.g. displaying examples in Sunrise), and continues
supporting OpenAPI 3.0 (and 2.0, aka Swagger 2).
Hint: The OpenAPI 3.1 major change is that Schema Object definitions are now
fully compliant with standard JSON Schema. It is an incompatible change since
OpenAPI-specific overrides and keywords like example, nullable, discriminator, xml
are removed from the Schema Object (see
OpenAPI Blog: Migrating from OpenAPI 3.0 to 3.1).
Check out the OpenAPI release page
for all change details.
Hint: You might find the OpenAPI Map a helpful tool supporting UI navigation for the OpenAPI 3.0 specification. (Newer OpenAPI versions are not yet supported.)
Hint: We do not yet provide guidelines for GraphQL and focus on resource oriented HTTP/REST API style (and related tooling and infrastructure support). Following our Zalando Tech Radar (internal_link), we think that GraphQL has no major benefits, but a couple of downsides compared to REST as API technology for general purpose peer-to-peer microservice communication. However, GraphQL can provide a lot of value for specific target domain problems, especially backends for frontends (BFF) and mobile clients, where typically many (domain object) resources from different services are queried and multiple roundtrip overhead should be avoided due to (mobile or public) network constraints. Therefore we list both technologies on ADOPT, though GraphQL only supplements REST for the BFF-specific problem domain.
SHOULD provide API user manual
In addition to the API Specification, it is good practice to provide an API user manual to improve client developer experience, especially of engineers that are less experienced in using this API. A helpful API user manual typically describes the following API aspects:
-
API scope, purpose, and use cases
-
concrete examples of API usage
-
edge cases, error situation details, and repair hints
-
architecture context and major dependencies - including figures and sequence flows
The user manual must be published online, e.g. via our documentation hosting
platform service, GHE pages, or specific team web servers. Please do not forget
to include a link to the API user manual into the API specification using the
#/externalDocs/url property.
MUST only use durable and immutable remote references
Normally, API specification files must be self-contained, i.e. files
should not contain references to local or remote content, e.g. ../fragment.yaml#/element or
$ref: 'https://github.com/zalando/zally/blob/master/server/src/main/resources/api/zally-api.yaml#/schemas/LintingRequest'.
The reason is, that the content referred to is in general not durable and
not immutable. As a consequence, the semantic of an API may change in
unexpected ways. (For example, the second link is already outdated due to code restructuring.)
However, you may use remote references to resources accessible by the following service URLs:
-
https://infrastructure-api-repository.zalandoapis.com/ (internal_link)– used to refer to user-defined, immutable API specification revisions published via the internal API repository. -
https://opensource.zalando.com/restful-api-guidelines/{model.yaml}– used to refer to guideline-defined re-usable API fragments (see{model.yaml}files in restful-api-guidelines/models for details).
Hint: The formerly used remote references to the Problem API fragment
(aliases https://opensource.zalando.com/problem/ and
https://zalando.github.io/problem/) are deprecated, but still supported for
compatibility (MUST support problem JSON on how to replace).
As we control these URLs, we ensure that their content is durable and immutable. This allows to define API specifications by using fragments published via these sources, as suggested in MUST specify success and error responses.
5. REST Basics - Meta information
MUST contain API meta information
API specifications must contain the following OpenAPI meta information:
-
#/info/titlea (unique) identifying, functional descriptive name of the API -
#/info/versionthe API specification document version following MUST use semantic versioning -
#/info/descriptiona proper description of the API -
#/info/contact/{name,url,email}contact info of the team owning the API specification
The following OpenAPI extension properties must be additionally provided:
-
#/info/x-api-idunique identifier of the API (see rule 215) -
#/info/x-audienceintended target audience of the API (see rule 219)
MUST use semantic versioning
OpenAPI requires the definition of API specification version via #/info/version.
Note, this API specification document version is distinct from the
OpenAPI Specification version (also required, e.g. openapi: 3.1.0),
or the API Implementation version — see Basic Terminology.
We expect API designers to comply to
Semantic Versioning 2.0 rules 1 - 8 and 11 with the standard version format
<MAJOR>.<MINOR>.<PATCH> as follows:
-
Increment the MAJOR version when you make incompatible API changes after having aligned the changes with consumers,
-
Increment the MINOR version when you add new functionality in a backwards-compatible manner, and
-
Optionally increment the PATCH version when you make backwards-compatible bug fixes or editorial changes not affecting the functionality.
Additional Notes:
-
Pre-release versions (rule 9) and build metadata (rule 10) must not be used in API version information.
-
While patch versions are useful for fixing typos etc, API designers are free to decide whether they increment it or not.
-
API designers should consider to use API version
0.y.z(rule 4) for initial API design.
Example:
openapi: 3.1.0
info:
version: 1.3.7
title: Parcel Service API
description: API for <...>
<...>
MUST provide API identifiers
Each API specification must be provisioned with a globally unique and
immutable API identifier. The API identifier is defined in the info-block
of the OpenAPI specification and must conform to the following definition:
/info/x-api-id:
type: string
format: urn
pattern: ^[a-z0-9][a-z0-9-:.]{6,62}[a-z0-9]$
description: |
Mandatory globally unique and immutable API identifier. The API
id allows to track the evolution and history of an API specification
as a sequence of versions.
API specifications will evolve and any aspect of an OpenAPI specification may change. We require API identifiers because we want to support API clients and providers with API lifecycle management features, like change trackability and history or automated backward compatibility checks. The immutable API identifier allows the identification of all API specification versions of an API evolution. By using API semantic version information or API publishing date as order criteria you get the version or publication history as a sequence of API specifications.
Note: While it is nice to use human readable API identifiers based on self-managed URNs, it is recommend to stick to a UUID (freshly generated when first creating the API) to relief API designers from any urge of changing the API identifier while evolving the API. Do not copy an API unless you immediately change the API identifier in it!
Example:
openapi: 3.1.0
info:
x-api-id: d0184f38-b98d-11e7-9c56-68f728c1ba70
title: Parcel Service API
description: API for <...>
version: 1.5.8
<...>
MUST provide API audience
Each API must be classified with respect to the intended target audience supposed to consume the API, to facilitate differentiated standards on APIs for discoverability, changeability, quality of design and documentation, as well as permission granting. We differentiate the following API audience groups with clear organisational and legal boundaries:
- component-internal
-
This is often referred to as a team internal API or a product internal API. The API consumers with this audience are restricted to applications of the same functional component which typically represents a specific product with clear functional scope and ownership. All services of a functional component / product are owned by a specific dedicated owner and engineering team(s). Typical examples of component-internal APIs are APIs being used by internal helper and worker services or that support service operation.
- business-unit-internal
-
The API consumers with this audience are restricted to applications of a specific product portfolio owned by the same business unit.
- company-internal
-
The API consumers with this audience are restricted to applications owned by the business units of the same the company (e.g. Zalando company with Zalando SE, Zalando Payments SE & Co. KG. etc.)
- external-partner
-
The API consumers with this audience are restricted to applications of business partners of the company owning the API and the company itself.
- external-public
-
APIs with this audience can be accessed by anyone with Internet access.
Note: a smaller audience group is intentionally included in the wider group and thus does not need to be declared additionally.
The API audience is provided as API meta information in the info-block of
the OpenAPI specification and must conform to the following specification:
/info/x-audience:
type: string
x-extensible-enum:
- component-internal
- business-unit-internal
- company-internal
- external-partner
- external-public
description: |
Intended target audience of the API. Relevant for standards around
quality of design and documentation, reviews, discoverability,
changeability, and permission granting.
Note: Exactly one audience per API specification is allowed. For this reason a smaller audience group is intentionally included in the wider group and thus does not need to be declared additionally. If parts of your API have a different target audience, we recommend to split API specifications along the target audience — even if this creates redundancies (rationale (internal_link)).
Example:
openapi: 3.1.0
info:
x-audience: company-internal
title: Parcel Helper Service API
description: API for <...>
version: 1.2.4
<...>
For details and more information on audience groups see the API Audience narrative (internal_link).
MUST/SHOULD/MAY use functional naming schema
Functional naming is a powerful, yet easy way to align global resources as host, permission, and event names within an application landscape. It helps to preserve uniqueness of names while giving readers meaningful context information about the addressed component. Besides, the most important aspect is, that it allows to keep APIs stable in the case of technical and organizational changes (Zalando for example maintains an internal naming convention).
A unique functional-name is assigned to each functional component serving an API.
It is built of the domain name of the functional group the component is belonging
to and a unique a short identifier for the functional component itself:
<functional-name> ::= <functional-domain>-<functional-component>
<functional-domain> ::= [a-z][a-z0-9-]* -- managed functional group of components
<functional-component> ::= [a-z][a-z0-9-]* -- name of API owning functional component
Depending on the API audience, you must/should/may follow the functional naming schema for hostnames and event names (and also permission names, in future) as follows:
Functional Naming |
Audience |
must |
external-public, external-partner |
should |
company-internal, business-unit-internal |
may |
component-internal |
Please see the following rules for detailed functional naming patterns: * MUST follow naming convention for hostnames * MUST follow naming convention for event type names
Internal Guideance: You must use the simple
functional name registry (internal_link)
to register your functional name before using
it. The registry is a centralized infrastructure service to ensure uniqueness
of your functional names (and available domains — including subdomains) and
to support hostname DNS resolution.
Hint: Due to lexicalic restrictions of DNS names there is no specific separator
to split a functional name into (sub) domain and component; this knowledge is only
managed in the registry.
MUST follow naming convention for hostnames
Hostnames in APIs must, respectively should conform to the functional naming
depending on the audience as follows (see MUST/SHOULD/MAY use functional naming schema for details and
<functional-name> definition):
<hostname> ::= <functional-hostname> | <application-hostname>
<functional-hostname> ::= <functional-name>.zalandoapis.com
Hint: The following convention (e.g. used by legacy STUPS infrastructure) is deprecated and only allowed for hostnames of component-internal APIs:
<application-hostname> ::= <application-id>.<organization-unit>.zalan.do
<application-id> ::= [a-z][a-z0-9-]* -- application identifier
<organization-id> ::= [a-z][a-z0-9-]* -- organization unit identifier, e.g. team identifier
Exception: There are legacy hostnames used for APIs with external-partner audience
which may not follow this rule due to backward compatibility constraints.
The API Linter maintains an allow-list for these exceptions (including e.g.
api.merchants.zalando.com and api-sandbox.merchants.zalando.com).
6. REST Basics - Security
MUST secure endpoints
Every API endpoint must be protected and armed with authentication and authorization.
As part of the API specification you must define how you protect your API using
either the http typed bearer or oauth2 typed security schemes defined in the
OpenAPI Authentication Specification.
The majority of our APIs (especially the company internal APIs) are protected
using JWT tokens provided by the platform IAM token service. In these situations
you should use the http typed
Bearer Authentication
security scheme — it is based on OAuth2.0 RFC 6750 defining the standard header
Authorization: Bearer <token>.
The following code snippet shows how to define the bearer security scheme.
components:
securitySchemes:
BearerAuth:
type: http
scheme: bearer
bearerFormat: JWT
The bearer security scheme can then be applied to all API endpoints, e.g. requiring
the token to have api-repository.read scope for permission as follows (see
also MUST define and assign permissions (scopes)):
security:
- BearerAuth: [ api-repository.read ]
In other, more specific situations e.g. with customer and partner facing APIs you
may use other OAuth 2.0 authorization flows as defined by RFC 6749.
Please consult the
OpenAPI OAuth 2.0 Authentication
section for details on how to define oauth2 typed security schemes correctly.
Note: Do not use OpenAPI oauth2 typed security scheme flows (e.g. implicit)
if your service does not fully support it and implements a simple bearer token scheme,
because it exposes authentication server address details and may make use of redirection.
MUST define and assign permissions (scopes)
Endpoints must be equipped with permissions, if they require client authorization for protection
since e.g. data is exposed that is classified as orange or red according to Zalando’s
Data Classification Group Policy (internal link).
Please refer to MUST follow the naming convention for permissions (scopes) for designing permission names.
Some API endpoints may not require specific permissions for authorization e.g.
in case of (i) authorization is not needed for the endpoint since all
exposed data is classified as green or yellow,
or in case of (ii) the specific authorization is provided differently on
the individual object level. In these situations, however, you must make
it explicit by assigning the uid pseudo permission, which is always
available as OAuth2 default scope for all clients in Zalando.
The defined permissions are assigned to each API endpoint based on the security schema (see example in previous section) by specifying the security requirement as follows:
paths:
/business-partners/{partner-id}:
get:
summary: Retrieves information about a business partner
security:
- BearerAuth: [ business-partner-service.read ]
Hint: Following a minimal API specification approach, the
Authorization-header does not need to be defined on each API endpoint, since
it is required and so to say implicitly defined via the security section.
MUST follow the naming convention for permissions (scopes)
As long as the functional naming is not yet supported by our permission registry, permission names in APIs must conform to the following naming pattern:
<permission> ::= <standard-permission> | -- should be sufficient for majority of use cases
<resource-permission> | -- for special security access differentiation use cases
<pseudo-permission> -- used to explicitly indicate that access is not restricted
<standard-permission> ::= <application-id>.<access-mode>
<resource-permission> ::= <application-id>.<resource-name>.<access-mode>
<pseudo-permission> ::= uid
<application-id> ::= [a-z][a-z0-9-]* -- application identifier
<resource-name> ::= [a-z][a-z0-9-]* -- free resource identifier
<access-mode> ::= read | write -- might be extended in future
Note: This naming convention only applies to scopes for service-to-service communication using the Platform IAM tokens. For IAM systems with other naming rules (e.g. Zalando Partner IAM), the naming should be consistent with the existing conventions of those systems.
The permission naming schema corresponds to the naming schema for hostnames and event type names, and typical examples are:
| Application ID | Resource ID | Access Type | Example |
|---|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Note: APIs should stick to component specific permissions without resource extension to avoid the complexity of too many fine grained permissions. For the majority of use cases, restricting access for specific API endpoints using read or write is sufficient.
7. REST Basics - Data formats
MUST use standard data formats
Open API (based on JSON Schema Validation vocabulary) defines formats from ISO and IETF standards for date/time, integers/numbers and binary data. You must use these formats, whenever applicable:
OpenAPI type |
OpenAPI format |
Specification | Example |
|---|---|---|---|
|
|
4 byte signed integer between -231 and 231-1 |
|
|
|
8 byte signed integer between -263 and 263-1 |
|
|
|
arbitrarily large signed integer number |
|
|
|
|
|
|
|
|
|
|
|
arbitrarily precise signed decimal number |
|
|
|
|
|
|
|
|
|
|
|
Local date syntactically defined as `full-date in RFC 3339 as subset of ISO 8601 |
|
|
|
UTC time defined as full-time in RFC 3339 as subset of ISO 8601 |
|
|
|
|
|
|
|
non-UTC wall time syntactically defined as |
|
|
|
Format |
|
|
|
Time-zone id as defined by the IANA time zone database standard (including daylight saving time definitions). |
|
|
|
defined in RFC 3339 according to ISO 8601, see also rule #127 for details. |
|
|
|
defined in RFC 3339 according to ISO 8601, see also rule #127 for details. |
|
|
|
|
|
|
|
||
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
||
|
|
|
|
|
|
|
|
|
|
regular expressions as defined in ECMA 262 |
|
Note: Formats bigint and decimal have been added to the OpenAPI defined formats — see also MUST define a format for number and integer types and MUST use standard formats for date and time properties below.
We add further OpenAPI formats that are useful especially in an e-commerce environment
e.g. language code, country code, and currency based other ISO and IETF standards.
You must use these formats, whenever applicable:
OpenAPI type |
format |
Specification | Example |
|---|---|---|---|
|
|
two letter language code — see ISO 639-1. Hint: In the past we used |
|
|
|
multi letter language tag — see BCP 47. It is a compatible extension of ISO 639-1 optionally with additional information for language usage, like region, variant, script. |
|
|
|
two letter country code — see ISO 3166-1 alpha-2. Hint: In the past we used |
|
|
|
three letter currency code — see ISO 4217 |
|
|
|
Global Trade Item Number — see GTIN |
|
Remark: Please note that this list of standard data formats is not exhaustive and everyone is encouraged to propose additions.
MUST define a format for number and integer types
In MUST use standard data formats we added bigint and decimal to the OpenAPI defined formats.
As an implication, you must always provide one of the formats int32, int64, bigint
or float, double, decimal when you define an API property of
JSON type number or integer.
By this we prevent clients from guessing the precision incorrectly, and thereby
changing the value unintentionally. The precision must be translated by clients
and servers into the most specific language types; in Java, for instance, the number
type with decimal format will translate into BigDecimal and integer type with
int32 format will translate to int or Integer Java types.
MUST encode binary data in base64url
You may expose binary data. You must use a standard media type and data format,
if applicable — see Rule 168. If no standard is available, you must define
the binary data as string typed property with binary format using base64url
encoding — as also described in MUST use standard data formats.
MUST use standard formats for date and time properties
As a specific case of MUST use standard data formats, you must use the string typed formats
date, time-local, date-time-local, time, date-time, duration, or period for the definition of date and time properties.
The formats are based on the standard RFC 3339 internet profile which is a
subset of ISO 8601.
APIs MUST use the upper-case T as a separator between date and time and
upper-case Z at the end when generating time or date-time — as opposed to lower-case t,
z which are also accepted in RFC 3339.
Exception: For passing date/time information via standard protocol headers, HTTP RFC 7231 requires to follow the date and time specification used by the Internet Message Format RFC 5322.
As defined by the standard, time and date-time relates to UTC and may be optionally
equipped with an offset.However, we recommend to only use times without offsets, for example 2015-05-28T14:07:17Z
instead of 2015-05-28T14:07:17+00:00 or 2015-05-28T13:07:17+01:00.
In particular, we recommend storing all dates consistently in UTC without offset.
It supports easy time comparisons, and from experience we learned that time
offsets are not easy to understand, different to time-zones and often not correctly handled.
Localization should be done locally by the services that provide
user interfaces, if required.
Hint: We discourage using numerical timestamps. It typically creates
issues with precision, e.g. whether to represent a timestamp as 1460062925,
1460062925000 or 1460062925.000. Using date-time strings avoid this ambiguity.
SHOULD use appropriate formats for date and time properties
When using standard formats for date and time properties you should take the following into account:
-
date-timeshould be used where an exact point-in-time is required, for instance, datetimes for supplier advice or specific processing events. It explicitly relates to UTC (with an optional numeric offset) avoiding misinterpretations and eliminating the need for additional time-zone context to determine the exact point-in-time. Note, UTC times with offsets are different from local times supplemented with a time-zone field which may include daylight saving times. -
dateshould be used for properties where no exact point in time is required and day time-range is represented, for instance, document dates, birthdays, ETAs (estimated time of arrival). Without further context,dateimplies the time period from midnight to midnight in the local time zone. However, the timezone information can be provided as an additional field intz-idformat. -
time-localanddate-time-localare not related to UTC and without offset or Locale information. Adate-time-localfield must be supplemented with an additional time-zone field intz-idformat (which may include daylight saving time information) in order to define an exact point-in-time. Adate-time-localfield is e.g. used as start date of international campaigns where the time-zone is part of the market configuration determining the exact point-in-time. Atime-localfield represents local wall time and no exact point-in-time. It is e.g. used for the start time of periodic events like shop opening hours, often supplemented with additional time-zone information.
SHOULD use standard formats for time duration and interval properties
Properties and that are by design durations and time intervals should be
represented as strings in the format defined by ISO 8601
and the (RFC 3339 Appendix A grammar for durations
and periods (the latter called time intervals in ISO 8601). ISO
8601:1-2019 defines an extension (..) to express open ended time intervals
that are very convenient in searches and are included in the below
ABNF grammar:
dur-second = 1*DIGIT "S"
dur-minute = 1*DIGIT "M" [dur-second]
dur-hour = 1*DIGIT "H" [dur-minute]
dur-time = "T" (dur-hour / dur-minute / dur-second)
dur-day = 1*DIGIT "D"
dur-week = 1*DIGIT "W"
dur-month = 1*DIGIT "M" [dur-day]
dur-year = 1*DIGIT "Y" [dur-month]
dur-date = (dur-day / dur-month / dur-year) [dur-time]
duration = "P" (dur-date / dur-time / dur-week)
period-explicit = iso-date-time "/" iso-date-time
period-start = iso-date-time "/" (duration / "..")
period-end = (duration / "..") "/" iso-date-time
period = period-explicit / period-start / period-end
Naming: A time interval query parameter should use <time-property>_between instead
of the parameter pair <time-property>_before/<time-property>_after, while
properties providing a time interval should be named <time-property>_interval.
MUST use standard formats for country, language and currency properties
As a specific case of MUST use standard data formats you must use the following standard formats:
-
Country codes: ISO 3166-1-alpha-2 two letter country codes indicated via format
iso-3166-alpha-2in the OpenAPI specification. -
Language codes: ISO 639-1 two letter language codes indicated via format
iso-639-1in the OpenAPI specification. -
Language variant tags: BCP 47 multi letter language tag indicated via format
bcp47in the OpenAPI specification. (It is a compatible extension of ISO 639-1 with additional optional information for language usage, like region, variant, script) -
Currency codes: ISO 4217 three letter currency codes indicated via format
iso-4217in the OpenAPI specification.
SHOULD use content negotiation, if clients may choose from different resource representations
In some situations the API supports serving different representations of a
specific resource (at the same URL), e.g. JSON, PDF, TEXT, or HTML
representations for an invoice resource. You should use
content negotiation to
support clients specifying via the standard HTTP headers Accept,
Accept-Language, Accept-Encoding which representation is best suited for
their use case, for example, which language of a document, representation /
content format, or content encoding. You SHOULD use standard media types like application/json or
application/pdf for defining the content format in the Accept header.
SHOULD only use UUIDs if necessary
Generating IDs can be a scaling problem in high frequency and near real time use cases. UUIDs solve this problem, as they can be generated without collisions in a distributed, non-coordinated way and without additional server round trips.
However, they also come with some disadvantages:
-
pure technical key without meaning; not ready for naming or name scope conventions that might be helpful for pragmatic reasons, e.g. we learned to use names for product attributes, instead of UUIDs
-
less usable, because…
-
cannot be memorized and easily communicated by humans
-
harder to use in debugging and logging analysis
-
less convenient for consumer facing usage
-
-
quite long: readable representation requires 36 characters and comes with higher memory and bandwidth consumption
-
not ordered along their creation history and no indication of used id volume
-
may be in conflict with additional backward compatibility support of legacy ids
UUIDs should be avoided when not needed for large scale id generation. Instead,
for instance, server side support with id generation can be preferred (POST
on id resource, followed by idempotent PUT on entity resource). Usage of
UUIDs is especially discouraged as primary keys of master and configuration
data, like brand-ids or attribute-ids which have low id volume but widespread
steering functionality.
Please be aware that sequential, strictly monotonically increasing numeric identifiers may reveal critical, confidential business information, like order volume, to non-privileged clients.
In any case, we should always use string rather than number type for identifiers. This gives us more flexibility to evolve the identifier naming scheme. Accordingly, if used as identifiers, UUIDs should not be qualified using a format property.
Hint: Usually, random UUID is used - see UUID version 4 in RFC 4122. Though UUID version 1 also contains leading timestamps it is not reflected by its lexicographic sorting. This deficit is addressed by ULID (Universally Unique Lexicographically Sortable Identifier). You may favour ULID instead of UUID, for instance, for pagination use cases ordered along creation time.
8. REST Basics - URLs
Guidelines for naming and designing resource paths and query parameters.
SHOULD not use /api as base path
In most cases, all resources provided by a service are part of the public API, and therefore should be made available under the root "/" base path.
If the service should also support non-public, internal APIs
— for specific operational support functions, for example — we encourage
you to maintain two different API specifications and provide
API audience. For both APIs, you should not use /api as base path.
We see API’s base path as a part of deployment variant configuration. Therefore, this information has to be declared in the server object.
MUST pluralize resource names
Usually, a collection of resource instances is provided (at least the API
should be ready here). The special case of a resource singleton must
be modeled as a collection with cardinality 1 including definition of
maxItems = minItems = 1 for the returned array structure
to make the cardinality constraint explicit.
Exception: the pseudo identifier self used to specify a resource endpoint
where the resource identifier is provided by authorization information (see MUST identify resources and sub-resources via path segments).
MUST use URL-friendly resource identifiers
To simplify encoding of resource IDs in URLs they must match the regex [a-zA-Z0-9:._\-/]*.
Resource IDs only consist of ASCII strings using letters, numbers, underscore, minus, colon,
period, and - on rare occasions - slash.
Note: slashes are only allowed to build and signal resource identifiers consisting of compound keys.
Note: to prevent ambiguities of unnormalized paths resource identifiers must never be empty. Consequently, support of empty strings for path parameters is forbidden.
MUST use kebab-case for path segments
Path segments are restricted to ASCII kebab-case strings matching regex ^[a-z][a-z\-0-9]*$.
The first character must be a lower case letter, and subsequent
characters can be a letter, or a dash(-), or a number.
Example:
/shipment-orders/{shipment-order-id}
Hint: kebab-case applies to concrete path segments and not necessarily the names of path parameters.
MUST use normalized paths without empty path segments and trailing slashes
You must not specify paths with duplicate or trailing slashes, e.g.
/customers//addresses or /customers/. As a consequence, you must also not
specify or use path variables with empty string values.
Note: Non standard paths have no clear semantics. As a result, behavior for non standard paths varies between different HTTP infrastructure components and libraries. This may leads to ambiguous and unexpected results during request handling and monitoring.
We recommend to implement services robust against clients not following this rule. All services should normalize request paths before processing by removing duplicate and trailing slashes. Hence, the following requests should refer to the same resource:
GET /orders/{order-id}
GET /orders/{order-id}/
GET /orders//{order-id}
Note: path normalization is not supported by all framework out-of-the-box. Services are required to support at least the normalized path while rejecting all alternatives paths, if failing to deliver the same resource.
MUST keep URLs verb-free
The API describes resources, so the only place where actions should appear is in the HTTP methods. In URLs, use only nouns. Instead of thinking of actions (verbs), it’s often helpful to think about putting a message in a letter box: e.g., instead of having the verb cancel in the url, think of sending a message to cancel an order to the cancellations letter box on the server side.
MUST avoid actions — think about resources
REST is all about your resources, so consider the domain entities that take
part in web service interaction, and aim to model your API around these using
the standard HTTP methods as operation indicators. For instance, if an
application has to lock articles explicitly so that only one user may edit
them, create an article lock with PUT or POST instead of using a lock
action.
Request:
PUT /article-locks/{article-id}
The added benefit is that you already have a service for browsing and filtering article locks.
SHOULD define useful resources
As a rule of thumb resources should be defined to cover 90% of all its client’s use cases. A useful resource should contain as much information as necessary, but as little as possible. A great way to support the last 10% is to allow clients to specify their needs for more/less information by supporting filtering and embedding.
MUST use domain-specific resource names
API resources represent elements of the application’s domain model. Using domain-specific nomenclature for resource names helps developers to understand the functionality and basic semantics of your resources. It also reduces the need for further documentation outside the API specification. For example, "sales-order-items" is superior to "order-items" in that it clearly indicates which business object it represents. Along these lines, "items" is too general.
SHOULD model complete business processes
An API should contain the complete business processes containing all resources representing the process. This enables clients to understand the business process, foster a consistent design of the business process, allow for synergies from description and implementation perspective, and eliminates implicit invisible dependencies between APIs.
In addition, it prevents services from being designed as thin wrappers around databases, which normally tends to shift business logic to the clients.
MUST identify resources and sub-resources via path segments
Some API resources may contain or reference sub-resources. Embedded sub-resources, which are not top-level resources, are parts of a higher-level resource and cannot be used outside of its scope. Sub-resources should be referenced by their name and identifier in the path segments as follows:
/resources/{resource-id}/sub-resources/{sub-resource-id}
In order to improve the consumer experience, you should aim for intuitively
understandable URLs, where each sub-path is a valid reference to a resource or
a set of resources. For instance, if
/partners/{partner-id}/addresses/{address-id} is valid, then, in principle,
also /partners/{partner-id}/addresses, /partners/{partner-id} and
/partners must be valid. Examples of concrete url paths:
/shopping-carts/de:1681e6b88ec1/items/1
/shopping-carts/de:1681e6b88ec1
/content/images/9cacb4d8
/content/images
Note: resource identifiers may be build of multiple other resource identifiers (see MAY expose compound keys as resource identifiers).
Exception: In some situations the resource identifier is not passed as a
path segment but via the authorization information, e.g. an authorization
token or session cookie. Here, it is reasonable to use self as
pseudo-identifier path segment. For instance, you may define /employees/self
or /employees/self/personal-details as resource paths — and may additionally
define endpoints that support identifier passing in the resource path, like
define /employees/{empl-id} or /employees/{empl-id}/personal-details.
MAY expose compound keys as resource identifiers
If a resource is best identified by a compound key consisting of multiple other resource identifiers, it is allowed to reuse the compound key in its natural form containing slashes instead of technical resource identifier in the resource path without violating the above rule MUST identify resources and sub-resources via path segments as follows:
/resources/{compound-key-1}[delim-1]...[delim-n-1]{compound-key-n}
Example paths:
/shopping-carts/{country}/{session-id}
/shopping-carts/{country}/{session-id}/items/{item-id}
/api-specifications/{docker-image-id}/apis/{path}/{file-name}
/api-specifications/{repository-name}/{artifact-name}:{tag}
/article-size-advices/{sku}/{sales-channel}
Note: Exposing a compound key as described above limits ability to evolve the structure of the resource identifier as it is no longer opaque.
To compensate for this drawback, APIs must apply a compound key abstraction consistently in all requests and responses parameters and attributes allowing consumers to treat these as technical resource identifier replacement. The use of independent compound key components must be limited to search and creation requests, as follows:
# compound key components passed as independent search query parameters
GET /article-size-advices?skus=sku-1,sku-2&sales_channel_id=sid-1
=> { "items": [{ "id": "id-1", ... },{ "id": "id-2", ... }] }
# opaque technical resource identifier passed as path parameter
GET /article-size-advices/id-1
=> { "id": "id-1", "sku": "sku-1", "sales_channel_id": "sid-1", "size": ... }
# compound key components passed as mandatory request fields
POST /article-size-advices { "sku": "sku-1", "sales_channel_id": "sid-1", "size": ... }
=> { "id": "id-1", "sku": "sku-1", "sales_channel_id": "sid-1", "size": ... }
Where id-1 is representing the opaque provision of the compound key
sku-1/sid-1 as technical resource identifier.
Remark: A compound key component may itself be used as another resource
identifier providing another resource endpoint, e.g /article-size-advices/{sku}.
MAY consider using (non-) nested URLs
If a sub-resource is only accessible via its parent resource and may not exist without parent resource, consider using a nested URL structure, for instance:
/shoping-carts/de/1681e6b88ec1/cart-items/1
However, if the resource can be accessed directly via its unique id, then the API should expose it as a top-level resource. For example, customer has a collection for sales orders; however, sales orders have globally unique id and some services may choose to access the orders directly, for instance:
/customers/1637asikzec1
/sales-orders/5273gh3k525a
SHOULD limit number of resource types
To keep maintenance and service evolution manageable, we should follow "functional segmentation" and "separation of concern" design principles and do not mix different business functionalities in same API. In practice this means that the number of resource types exposed via an API should be limited. In this context a resource type is defined as a set of highly related resources such as a collection, its members and any direct sub-resources.
For example, the resources below would be counted as three resource types, one for customers, one for the addresses, and one for the customers' related addresses:
/customers
/customers/{id}
/customers/{id}/preferences
/customers/{id}/addresses
/customers/{id}/addresses/{addr}
/addresses
/addresses/{addr}
Note that:
-
We consider
/customers/part of theid/preferences/customersresource type because it has a one-to-one relation to the customer without an additional identifier. -
We consider
/customersand/customers/as separate resource types becauseid/addresses/customers/also exists with an additional identifier for the address.id/addresses/{addr} -
We consider
/addressesand/customers/as separate resource types because there’s no reliable way to be sure they are the same.id/addresses
Given this definition, our experience is that well defined APIs involve no more than 4 to 8 resource types. There may be exceptions with more complex business domains that require more resources, but you should first check if you can split them into separate subdomains with distinct APIs.
Nevertheless one API should hold all necessary resources to model complete business processes helping clients to understand these flows.
SHOULD limit number of sub-resource levels
There are main resources (with root url paths) and sub-resources (or nested resources with non-root urls paths). Use sub-resources if their life cycle is (loosely) coupled to the main resource, i.e. the main resource works as collection resource of the subresource entities. You should use ⇐ 3 sub-resource (nesting) levels — more levels increase API complexity and url path length. (Remember, some popular web browsers do not support URLs of more than 2000 characters.)
MUST stick to conventional query parameters
If you provide query support for searching, sorting, filtering, and paginating, you must stick to the following naming conventions:
-
q: default query parameter, e.g. used by browser tab completion; should have an entity specific alias, e.g. sku. -
sort: comma-separated list of fields (as defined by MUST define collection format of header and query parameters) to define the sort order. To indicate sorting direction, fields may be prefixed with+(ascending) or-(descending), e.g. /sales-orders?sort=+id. -
fields: field name expression to retrieve only a subset of fields of a resource. See SHOULD support partial responses via filtering below. -
embed: field name expression to expand or embedded sub-entities, e.g. inside of an article entity, expand silhouette code into the silhouette object. Implementingembedcorrectly is difficult, so do it with care. See SHOULD allow optional embedding of sub-resources below. -
offset: numeric offset of the first element provided on a page representing a collection request. See REST Design - Pagination section below. -
cursor: an opaque pointer to a page, never to be inspected or constructed by clients. It usually (encrypted) encodes the page position, i.e. the identifier of the first or last page element, the pagination direction, and the applied query filters to recreate the collection. See Cursor-based pagination in RESTful APIs or REST Design - Pagination section below. -
limit: client suggested limit to restrict the number of entries on a page. See REST Design - Pagination section below.
9. REST Basics - JSON payload
These guidelines provides recommendations for defining JSON data at Zalando. JSON here refers to RFC 7159 (which updates RFC 4627), the "application/json" media type and custom JSON media types defined for APIs. The guidelines clarifies some specific cases to allow Zalando JSON data to have an idiomatic form across teams and services.
MUST use JSON as payload data interchange format
Use JSON (RFC 7159) to represent structured (resource) data passed with HTTP requests and responses as body payload. The JSON payload must use a JSON object as top-level data structure (if possible) to allow for future extension. This also applies to collection resources, where you ad-hoc would use an array — see also MUST always return JSON objects as top-level data structures.
Additionally, the JSON payload must comply to the more restrictive Internet JSON (RFC 7493), particularly
-
Section 2.1 on encoding of characters, and
-
Section 2.3 on object constraints.
As a consequence, a JSON payload must
-
use
UTF-8encoding -
consist of valid Unicode strings, i.e. must not contain non-characters or surrogates, and
-
contain only unique member names (no duplicate names).
SHOULD design single resource schema for reading and writing
To simplify API specs and API maintenance, as well as the cognitive load of developers, endpoints should utilize a common model for reading and writing the same resource type. The differences between read and write models are best addressed by
-
marking properties
writeOnlythat are only available in a request, e.g. passwords, and -
marking properties
readOnlythat are only available in a response, e.g. resource identifiers.
Note: A resource with property marked readOnly in the API according to
the JSON schema validation may be
ignored or rejected by a server. Both are in line with the idea behind the compatibility guidance, however, we suggest to document when rejecting
to prevent client side surprises.
SHOULD be aware of services not fully supporting JSON/unicode
JSON payloads passed via API requests consist of valid unicode characters
(see MUST use JSON as payload data interchange format). While \uxxxx are valid characters in a JSON strings, they can
create failures when leaving the API request processing context, e.g. by
writing the data into a database or piping it through command line tools that
are not 100% compatible with the JSON or unicode standard.
A prominent example for such a tool is the Postgres database:
-
Postgres cannot handle
\u0000injsonbandtexttypes (see datatype-json).
As a consequence, servers and clients that forward JSON content to other tools should check that these tools fully support the JSON or unicode standard. If not, they should reject or sanitize unicode characters not supported by the tools.
Note: A sanitization and rejection are actions that change the API behavior and therefore should be described by the API specification.
MAY pass non-JSON media types using data specific standard formats
Non-JSON media types may be supported, if you stick to a business object specific standard format for the payload data, for instance, image data format (JPG, PNG, GIF), document format (PDF, DOC, ODF, PPT), or archive format (TAR, ZIP).
Generic structured data interchange formats other than JSON (e.g. XML, CSV) may be provided, but only additionally to JSON as default format using content negotiation, for specific use cases where clients may not interpret the payload structure.
SHOULD use standard media types
You should use standard media types (defined in media type registry
of Internet Assigned Numbers Authority (IANA)) as content-type (or accept) header
information. More specifically, for JSON payload you should use the standard media type
application/json (or application/problem+json for MUST support problem JSON).
You should avoid using custom media types like application/x.zalando.article+json.
Custom media types beginning with x bring no advantage compared to the
standard media type for JSON, and make automated processing more difficult.
Exception: Custom media type should be only used in situations where you need to provide API endpoint versioning (with content negotiation) due to incompatible changes.
SHOULD pluralize array names
Names of arrays should be pluralized to indicate that they contain multiple values. This implies in turn that object names should be singular.
MUST property names must be snake_case (and never camelCase)
Property names are restricted to ASCII snake_case strings matching regex ^[a-z_][a-z_0-9]*$.
The first character must be a lower case letter, or an underscore, and subsequent
characters can be a letter, an underscore, or a number.
Examples:
customer_number, sales_order_number, billing_address
Rationale: No established industry standard exists, but many popular Internet companies prefer snake_case: e.g. GitHub, Stack Exchange, Twitter. Others, like Google and Amazon, use both - but not only camelCase. It’s essential to establish a consistent look and feel such that JSON looks as if it came from the same hand.
SHOULD declare enum values using UPPER_SNAKE_CASE string
Enumerations should be represented as string typed OpenAPI definitions of
request parameters or model properties.
Enum values (using enum, x-extensible-enum or extensible enums using examples)
need to consistently use the upper-snake case format, e.g. VALUE
or YET_ANOTHER_VALUE.
This approach allows to clearly distinguish enum values from properties or
other elements.
SHOULD use naming convention for date/time properties
Naming of date and date-time properties should comply with the following convention:
The name either (i) contains date, day, time, timestamp or similar type indicators,
or (ii) end with the _at suffix. The convention allows easy identification of date/time
typed properties and distinguishing them e.g. from boolean properties like created vs. created_at.
Examples of valid date/time property names:
-
created_at,modified_at,occurred_at,returned_at— instead ofcreated,modified, … -
campaign_start_time,arrival_date,checkout_time— instead ofcampaign_start,arrival, …
Hint: Use format: date-time or format: date as required in MUST use standard data formats.
SHOULD define maps using additionalProperties
A "map" here is a mapping from string keys to some other type. In JSON this is represented as an object, the key-value pairs being represented by property names and property values. In OpenAPI schema (as well as in JSON schema) they should be represented using additionalProperties with a schema defining the value type. Such an object should normally have no other defined properties.
The map keys don’t count as property names in the sense of rule 118, and can follow whatever format is natural for their domain. Please document this in the description of the map object’s schema.
Here is an example for such a map definition (the translations property):
components:
schemas:
Message:
description:
A message together with translations in several languages.
type: object
properties:
message_key:
type: string
description: The message key.
translations:
description:
The translations of this message into several languages.
The keys are [IETF BCP-47 language tags](https://tools.ietf.org/html/bcp47).
type: object
additionalProperties:
type: string
description:
the translation of this message into the language identified by the key.
An actual JSON object described by this might then look like this:
{ "message_key": "color",
"translations": {
"de": "Farbe",
"en-US": "color",
"en-GB": "colour",
"eo": "koloro",
"nl": "kleur"
}
}