RAML is a language for the definition of HTTP-based APIs that embody most or all of the principles of Representational State Transfer (REST). This document constitutes the RAML specification, an application of the YAML 1.2 specification. The RAML specification provides mechanisms for defining practically-RESTful APIs, creating client/server source code, and comprehensively documenting the APIs for users.
This document constitutes the RAML 1.0 specification. The consensus of specification authors and RAML 0.8 users determines the contents of this document. We strongly recommend that implementers and users of the RAML 0.8 specification update their software and API definitions to the RAML 1.0 specification.
Normative text describes one or both of the following kinds of elements:
- Vital elements of the specification
- Elements that contain the conformance language key words as defined by IETF RFC 2119 "Key words for use in RFCs to Indicate Requirement Levels"
Informative text is potentially helpful to the user, but dispensable. Informative text can be changed, added, or deleted editorially without negatively affecting the implementation of the specification. Informative text does not contain conformance keywords.
All text in this document is, by default, normative.
The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in IETF RFC 2119 "Key words for use in RFCs to Indicate Requirement Levels".
In this specification, API definition means an API using this specification.
RAML Specification refers to this document.
REST is used in the context of an API implemented using some or all of the principles of REST (Representational State Transfer), which was introduced and first defined in 2000 in Chapter 5, REST, of the doctoral dissertation "Architectural Styles and the Design of Network-based Software Architecture" by Roy Fielding.
A resource is the conceptual mapping to an entity or set of entities.
A trailing question mark in key names MAY denote an optional key.
A template URI refers to a URI parameter, which is a variable element, enclosed in curly brackets ({}
) inside a relative URI of a resource.
RAML fully supports Level 2 as defined in RFC6570 for URI Templates.
Throughout this specification, Markdown means GitHub-Flavored Markdown.
- Introduction
- What's New and Different in RAML 1.0
- Markup Language
- The Root of the Document
- RAML Data Types
- Resources and Nested Resources
- Methods
- Responses
- Resource Types and Traits
- Security Schemes
- Annotations
- Modularization
- References
This specification describes the RESTful API Modeling Language (RAML). RAML is a human- and machine-readable language for the definition of a RESTful application programming interface (API). RAML is designed to improve the specification of the API by providing a format that the API provider and API consumers can use as a mutual contract. RAML can, for example, facilitate providing user documentation and source code stubs for client and server implementations. Such provisions streamline and enhance the definition and development of interoperable applications that utilize RESTful APIs.
RAML introduces the innovative concept of resource types and traits for characterizing and reusing patterns of resources and associated methods. Using resource types and traits minimizes the repetition in a RESTful API design and promotes consistency within and across APIs.
This document is organized as follows:
- Basic Information. How to describe core aspects of the API, such as its name, title, location (or URI), and defaults and how to include supporting documentation for the API.
- Data Types. Modeling API data through a streamlined type system that encompasses JSON Schema and XML Schema (XSD).
- Resources. How to specify API resources and nested resources, as well as URI parameters in any URI templates.
- Methods. How to specify the methods on API resources and their request headers, query parameters, and request bodies.
- Responses. The specification of API responses, including status codes, media types, response headers, and response bodies.
- Resource Types and Traits. The optional use of RAML resource types and traits to characterize resources.
- Security. Specifying an API security scheme in RAML.
- Annotations. Extending a RAML specification by defining strongly-typed annotations and applying them throughout the specification.
- Includes, Libraries, Overlays, and Extensions. How an API definition can consist of externalized definition documents, packaging collections of such definitions into libraries, separating and overlaying layers of metadata on a RAML document, and extending an API specification with additional functionality.
- Data types: a unified, streamlined, and powerful way to model data wherever it appears in an API.
- Uniformly covers bodies, URI parameters, headers, and query parameters and eliminates the need for a separate formParameters construct
- Supports wrapping XML and JSON schemas, and referring to sub-schemas, but in many cases, obviates the schemas
- Simplifies coding, compared to JSON Schema or XML Schema (XSD), because it is YAML-based
- Examples: multiple examples, expressible in YAML, and annotatable, so semantics can be injected
- Annotations: a tried-and-tested, strongly-typed mechanism for extensibility
- Libraries: improved modularity for broad reuse of API artifacts
- Overlays and Extensions: increased extensibility through separated files
- Improved Security Schemes:
- Wider OAuth support
- Support for pass-through (key-based) security schemes
- Several smaller changes for consistency and expressivity
This specification uses YAML 1.2 as its underlying format. YAML is a human-readable data format that aligns well with the design goals of this specification. As in YAML, all nodes such as keys, values, and tags, are case-sensitive.
RAML API definitions MUST be YAML 1.2-compliant documents that begin with a REQUIRED YAML-comment line that indicates the RAML version, as follows:
#%RAML 1.0
title: My API
The first line of a RAML API definition document MUST begin with the text #%RAML followed by a single space followed by the text 1.0 and nothing else before the end of the line. RAML fragment documents begin similarly with the RAML version comment and a fragment identifier, but are not in themselves RAML API definition documents.
The media type application/raml+yaml and its associated file extension .raml SHALL be used to designate files containing RAML API definitions, RAML fragments, and files that contain RAML markup. RAML is also capable of including documents of other media types, such as “application/schema+json” and “application/yaml”.
To facilitate the automated processing of RAML documents, RAML imposes the following restrictions and requirements in addition to the core YAML 1.2 specification:
- The first line of a RAML file MUST consist of a YAML comment that specifies the RAML version. Therefore, RAML processors SHALL NOT completely ignore all YAML comments.
- The order of some properties at certain levels within a RAML document is significant. Therefore, processors SHALL preserve this ordering.
The root section of the RAML document describes the basic information about an API, such as its title and version. The root section also defines assets used elsewhere in the RAML document, such as types and traits.
Nodes in a RAML-documented API definition MAY appear in any order. Processors MUST preserve the order of nodes of the same kind within the same node of the definition tree. Examples of such nodes are resources that appear at the same level of the resource tree, methods for a given resource, parameters for a given method, and nodes at the same level in a given type. Processors MUST also preserve the order of items within arrays.
This example shows a small part of a RAML API definition for the GitHub v3 public API.
#%RAML 1.0
title: GitHub API
version: v3
baseUri: https://api.github.com
mediaType: application/json
securitySchemes:
oauth_2_0: !include securitySchemes/oauth_2_0.raml
types:
Gist: !include types/gist.raml
Gists: !include types/gists.raml
resourceTypes:
collection: !include types/collection.raml
traits:
securedBy: [ oauth_2_0 ]
/users:
type: collection
get:
The following table enumerates the possible nodes at the root of a RAML document:
Name | Description |
---|---|
title | A short, plain-text label for the API. Its value is a string. |
description? | A substantial, human-friendly description of the API. Its value is a string and MAY be formatted using markdown. |
version? | The version of the API, for example "v1". Its value is a string. |
baseUri? | A URI that serves as the base for URIs of all resources. Often used as the base of the URL of each resource containing the location of the API. Can be a template URI. |
baseUriParameters? | Named parameters used in the baseUri (template). |
protocols? | The protocols supported by the API. |
mediaType? | The default media types to use for request and response bodies (payloads), for example "application/json". |
documentation? | Additional overall documentation for the API. |
schemas? | An alias for the equivalent "types" node for compatibility with RAML 0.8. Deprecated - API definitions SHOULD use the "types" node because a future RAML version might remove the "schemas" alias with that node. The "types" node supports XML and JSON schemas. |
types? | Declarations of (data) types for use within the API. |
traits? | Declarations of traits for use within the API. |
resourceTypes? | Declarations of resource types for use within the API. |
annotationTypes? | Declarations of annotation types for use by annotations. |
(<annotationName>)? | Annotations to be applied to this API. An annotation is a map having a key that begins with "(" and ends with ")" where the text enclosed in parentheses is the annotation name, and the value is an instance of that annotation. |
securitySchemes? | Declarations of security schemes for use within the API. |
securedBy? | The security schemes that apply to every resource and method in the API. |
uses? | Imported external libraries for use within the API. |
/<relativeUri>? | The resources of the API, identified as relative URIs that begin with a slash (/). A resource node is one that begins with the slash and is either at the root of the API definition or a child of a resource node. For example, /users and /{groupId} . |
The "schemas" and "types" nodes are mutually exclusive and synonymous: processors MUST NOT allow both to be specified at the root-level of an API definition. We recommended using the "types" node instead of "schemas" because the schemas alias is deprecated and might be removed in a future RAML version.
The OPTIONAL documentation node includes a variety of documents that serve as user guides and reference documentation for the API. Such documents can clarify how the API works or provide technical and business context.
The value of the documentation node MUST be a sequence of one or more documents. Each document is a map that MUST have exactly two key-value pairs described in the following table:
Name | Description |
---|---|
title | Title of the document. Its value MUST be a non-empty string. |
content | Content of the document. Its value MUST be a non-empty string and MAY be formatted using markdown. |
This example shows an API definition having two user documents.
#%RAML 1.0
title: ZEncoder API
baseUri: https://app.zencoder.com/api
documentation:
- title: Home
content: |
Welcome to the _Zencoder API_ Documentation. The _Zencoder API_
allows you to connect your application to our encoding service
and encode videos without going through the web interface. You
may also benefit from one of our
[integration libraries](https://app.zencoder.com/docs/faq/basics/libraries)
for different languages.
- title: Legal
content: !include docs/legal.markdown
The OPTIONAL baseUri node specifies a URI as an identifier for the API as a whole, and MAY be used to specify the URL at which the API is served (its service endpoint), and which forms the base of the URLs of each of its resources. The value of the baseUri node is a string that MUST conform to the URI specification RFC2396 or a Template URI.
If the baseUri value is a Template URI, the following reserved base URI parameter is available.
URI Parameter | Value |
---|---|
version | The value of the root-level version node |
Any other URI template variables appearing in the baseUri MAY be described explicitly within a baseUriParameters node at the root of the API definition. The baseUriParameters node has the same semantics and therefore MUST follow the same structure as the uriParameters node on a resource node, except that it specifies parameters in the base URI rather than the relative URI of a resource.
The following example RAML API definition uses a Template URI as the base URI.
#%RAML 1.0
title: Salesforce Chatter REST API
version: v28.0
baseUri: https://na1.salesforce.com/services/data/{version}/chatter
The following example declares an explicit base URI parameter.
#%RAML 1.0
title: Amazon S3 REST API
version: 1
baseUri: https://{bucketName}.s3.amazonaws.com
baseUriParameters:
bucketName:
description: The name of the bucket
When the base URI ends in one or more slashes (/
), the trailing slashes are omitted in the absolute paths for the resources using that base URI. For example, in the following snippet, the absolute paths for the resources are http://api.test.com/common/users/:userId
and http://api.test.com/common/users/:userId/groups
.
baseUri: http://api.test.com/common/
/users:
/{userId}:
/groups:
In the following, more complicated example with consecutive slashes in multiple places, only trailing slashes in the base URI are collapsed, leading to these absolute paths to resources: //api.test.com//common/
, //api.test.com//common//users//:userId//
, and //api.test.com//common//users//:userId//groups//
.
baseUri: //api.test.com//common//
/:
/users/:
/{userId}/:
/groups//:
The OPTIONAL protocols node specifies the protocols that an API supports. If the protocols node is not explicitly specified, one or more protocols included in the baseUri node SHALL be used; if the protocols node is explicitly specified, such node specification SHALL override any protocol included in the baseUri node. The protocols node MUST be a non-empty array of strings, of values HTTP and/or HTTPS, and be case-insensitive.
The following is an example of an API endpoint that accepts both HTTP and HTTPS requests.
#%RAML 1.0
title: Salesforce Chatter REST API
version: v28.0
protocols: [ HTTP, HTTPS ]
baseUri: https://na1.salesforce.com/services/data/{version}/chatter
Specifying the OPTIONAL mediaType node sets the default media type for responses and requests that have a body. You do not need to specify the media type within every body definition.
The value of the mediaType node MUST be a sequence of media type strings or a single media type string. The media type applies to requests having a body, the expected responses, and examples using the same sequence of media type strings. Each value MUST conform to the media type specification in RFC6838.
This example shows a RAML snippet for an API that accepts and returns a JSON-formatted body. If the remainder of this API specification does not explicitly specify another media type, this API accepts and returns only JSON-formatted bodies.
#%RAML 1.0
title: New API
mediaType: application/json
This example shows a RAML snippet for an API that accepts and returns JSON- or XML-formatted bodies.
#%RAML 1.0
title: New API
mediaType: [ application/json, application/xml ]
Explicitly defining a mediaType
node for a body of an API request or response overrides the default media type, as shown in the following example. The resource /people
returns a Person[]
body in either JSON or XML. The resource /messages
overrides the default media type by explicitly defining an application/json
node. Therefore, the resource /messages
returns only a JSON-formatted body.
#%RAML 1.0
title: New API
mediaType: [ application/json, application/xml ]
types:
Person:
Another:
/people:
get:
responses:
200:
body: Person[]
/messages:
post:
body:
application/json:
type: Another
Specifying the OPTIONAL securedBy node sets the default security schemes for, and protects, every method of every resource in the API. The value of the node MUST be an array of security scheme names. See section Applying Security Schemes for more information, including how to resolve the application of multiple security schemes through inheritance.
The following example shows an API allowing access through either an OAuth 2.0 security scheme or an OAuth 1.1 security scheme.
#%RAML 1.0
title: Dropbox API
version: 1
baseUri: https://api.dropbox.com/{version}
securedBy: [ oauth_2_0, oauth_1_0 ]
securitySchemes:
oauth_2_0: !include securitySchemes/oauth_2_0.raml
oauth_1_0: !include securitySchemes/oauth_1_0.raml
RAML 1.0 introduces the notion of data types, which provide a concise and powerful way of describing the data in an API. Data types add rules for validating data against a type declaration. Valid data adheres to all rules for the type. Data types can describe a base or resource URI parameter, a query parameter, a request or response header, or a request or response body. Data types are built-in or custom. A built-in type can be used anywhere the API expects data. Custom types can be defined by extending the built-in types as well as named and used like built-in type. Extending types MUST NOT create any cyclic dependencies. A type can be extended inline.
The following RAML example defines a User type that includes type declarations for the firstname, lastname, and age properties. The example declares the properties to be of built-in types string and number. Later, the User type serves to describe the type (schema) for a payload.
#%RAML 1.0
title: API with Types
types:
User:
type: object
properties:
firstname: string
lastname: string
age: number
/users/{id}:
get:
responses:
200:
body:
application/json:
type: User
A RAML type declaration resembles a JSON Schema definition. In fact, RAML types can be used instead of JSON and XML schemas, or coexist with them. The RAML type syntax, however, is designed to be considerably easier and more succinct than JSON and XML schemas while retaining their flexibility and expressiveness. The following snippet shows a number of examples of type declarations:
#%RAML 1.0
title: My API with Types
mediaType: application/json
types:
Org:
type: object
properties:
onCall: AlertableAdmin
Head: Manager
Person:
type: object
properties:
firstname: string
lastname: string
title?: string
Phone:
type: string
pattern: "[0-9|-]+"
Manager:
type: Person
properties:
reports: Person[]
phone: Phone
Admin:
type: Person
properties:
clearanceLevel:
enum: [ low, high ]
AlertableAdmin:
type: Admin
properties:
phone: Phone
Alertable: Manager | AlertableAdmin
/orgs/{orgId}:
get:
responses:
200:
body:
application/json:
type: Org
This section is informative.
The RAML type system borrows from object oriented programming languages such as Java, as well as from XML Schema (XSD) and JSON Schema.
RAML Types in a nutshell:
- Types are similar to Java classes.
- Types borrow additional features from JSON Schema, XSD, and more expressive object oriented languages.
- You can define types that inherit from other types.
- Multiple inheritance is allowed.
- Types are split into four families: external, object, array, and scalar.
- Types can define two types of members: properties and facets. Both are inherited.
- Properties are regular, object oriented properties.
- Facets are special configurations. You specialize types based on characteristics of facet values. Examples: minLength, maxLength
- Only object types can declare properties. All types can declare facets.
- To specialize a scalar type, you implement facets, giving already defined facets a concrete value.
- To specialize an object type, you define properties.
Types SHALL either be declared inline where the API expects data, in an OPTIONAL types node at the root of the API, or in an included library. To declare a type, you MUST use a map where the key represents the name of the type and its value is a type declaration.
types:
Person: # key name
# value is a type declaration
A type declaration references another type, or wraps or extends another type by adding functional facets (e.g. properties) or non-functional facets (e.g. a description), or is a type expression that uses other types. Here are the facets that all type declarations can have; certain type declarations might have other facets:
Facet | Description |
---|---|
default? | A default value for a type. When an API request is completely missing the instance of a type, for example when a query parameter described by a type is entirely missing from the request, then the API must act as if the API client had sent an instance of that type with the instance value being the value in the default facet. Similarly, when the API response is completely missing the instance of a type, the client must act as if the API server had returned an instance of that type with the instance value being the value in the default facet. A special case is made for URI parameters: for these, the client MUST substitute the value in the default facet if no instance of the URI parameter was given. |
schema? | An alias for the equivalent "type" facet for compatibility with RAML 0.8. Deprecated - API definitions SHOULD use the "type" facet because the "schema" alias for that facet name might be removed in a future RAML version. The "type" facet supports XML and JSON schemas. |
type? | The type which the current type extends or just wraps. The value of a type node MUST be either a) the name of a user-defined type or b) the name of a built-in RAML data type (object, array, or one of the scalar types) or c) an inline type declaration. |
example? | An example of an instance of this type that can be used, for example, by documentation generators to generate sample values for an object of this type. The "example" facet MUST NOT be available when the "examples" facet is already defined. See section Examples for more information. |
examples? | Examples of instances of this type. This can be used, for example, by documentation generators to generate sample values for an object of this type. The "examples" facet MUST NOT be available when the "example" facet is already defined. See section Examples for more information. |
displayName? | An alternate, human-friendly name for the type |
description? | A substantial, human-friendly description of the type. Its value is a string and MAY be formatted using markdown. |
(<annotationName>)? | Annotations to be applied to this API. An annotation is a map having a key that begins with "(" and ends with ")" where the text enclosed in parentheses is the annotation name, and the value is an instance of that annotation. |
facets? | A map of additional, user-defined restrictions that will be inherited and applied by any extending subtype. See section User-defined Facets for more information. |
xml? | The capability to configure XML serialization of this type instance. |
enum? | An enumeration of all the possible values of instances of this type. The value is an array containing representations of these possible values; an instance of this type MUST be equal to one of these values. |
The "schema" and "type" facets are mutually exclusive and synonymous: processors MUST NOT allow both to be specified, explicitly or implicitly, inside the same type declaration. Therefore, the following examples are invalid:
types:
Person:
schema: # invalid as mutually exclusive with `type`
type: # invalid as mutually exclusive with `schema`
/resource:
get:
responses:
200:
body:
application/json: # start type declaration
schema: # invalid as mutually exclusive with `type`
type: # invalid as mutually exclusive with `schema`
We recommended using the "type" facet instead of "schema" because the schema alias is deprecated and might be removed in a future RAML version. Also, the "type" facet supports XML and JSON schemas.
The RAML type system defines the following built-in types:
- any
- object
- array
- union via type expression
- one of the following scalar types: number, boolean, string, date-only, time-only, datetime-only, datetime, file, integer, or nil
In addition to the built-in types, the RAML type system also allows for the definition of JSON or XML schemas.
The following diagram shows the inheritance tree, starting at the root-level with any
.
Every type, whether built-in or user-defined, has the any
type at the root of its inheritance tree. By definition, the any
type is a type which imposes no restrictions, i.e. any instance of data is valid against it.
The "base" type of any type is the type in its inheritance tree that directly extends the any
type at the root; thus, for example, if a custom type status
extends the built-in type integer
which extends the built-in type number
which extends the any
type, then the base type of status
is number
. Note that a type may have more than one base type.
The any
type has no additional facets.
All types that have the built-in object base type in their inheritance tree MAY use the following facets in their type declarations:
Facet | Description |
---|---|
properties? | The properties that instances of this type can or must have. |
minProperties? | The minimum number of properties allowed for instances of this type. |
maxProperties? | The maximum number of properties allowed for instances of this type. |
additionalProperties? | A Boolean that indicates whether an object instance MAY contain additional properties. Default: true |
discriminator? | Determines the concrete type of an individual object at runtime when, for example, payloads contain ambiguous types due to unions or inheritance. The value must match the name of one of the declared properties of a type. Unsupported practices are inline type declarations and using discriminator with non-scalar properties. |
discriminatorValue? | Identifies the declaring type. Requires including a discriminator facet in the type declaration. A valid value is an actual value that might identify the type of an individual object and is unique in the hierarchy of the type. Inline type declarations are not supported.Default: The name of the type |
Example:
#%RAML 1.0
title: My API With Types
types:
Person:
type: object
properties:
name:
required: true
type: string
Properties of object types are defined using the OPTIONAL properties facet. The RAML Specification calls the value of the properties
facet a "properties declaration". The properties declaration MUST be a map of keys and values. The keys are valid property names for declaring a type instance. The values MUST be either a name of a type or an inline type declaration.
The properties declaration MAY specify whether a property is required or optional. Alternatively, a trailing question mark (?
) in the key name MAY be used to indicate that a property is optional.
Facet | Description |
---|---|
required? | Specifies that the property is required or not. Default: true . |
The following example declares an object type having two properties:
types:
Person:
properties:
name:
required: true
type: string
age:
required: false
type: number
The following example shows a common idiom:
types:
Person:
properties:
name: string # equivalent to ->
# name:
# type: string
age?: number # optional property; equivalent to ->
# age:
# type: number
# required: false
When the required
facet on a property is specified explicitly in a type declaration, any question mark in its property name MUST be treated as part of the property name rather than as an indicator that the property is optional.
For example, in
types:
profile:
properties:
preference?:
required: true
The profile
type has a property named preference?
that includes the trailing question mark. The following snippets show two ways of making preference?
optional:
types:
profile:
properties:
preference?:
required: false
or
types:
profile:
properties:
preference??:
Note:
When an object type does not contain the "properties" facet, the object is assumed to be unconstrained and therefore capable of containing any properties of any type.
By default, any instance of an object MAY have additional properties beyond those specified in its data type properties
facet. Assume the following code is an instance of the data type Person
that is described in the previous section.
Person:
name: "John"
age: 35
note: "US" # valid additional property `note`
The property note
is not explicitly declared in the Person
data type, but is valid because all additional properties are valid by default.
To restrict the addition of properties, you MAY set the value of the additionalProperties
facet to false
, or you MAY specify regular expression patterns that match sets of keys and restrict their values. The latter are called "pattern properties". The patterns are delineated by pairs of opening and closing /
characters, as follows:
#%RAML 1.0
title: My API With Types
types:
Person:
properties:
name:
required: true
type: string
age:
required: false
type: number
/^note\d+$/: # restrict any properties whose keys start with "note"
# followed by a string of one or more digits
type: string
This pattern property restricts any additional properties whose keys start with "note" followed by a string of one or more digits. Consequently, the example of an object instance that declares an additional note1
property with the value "US" is valid, but the property note2
is invalid with a non-string value:
Person:
name: "John"
age: 35
note1: "US" # valid
note2: 123 # not valid as it is not a string
note: 123 # valid as it does not match the pattern
To force all additional properties to be strings, regardless of their keys, use:
#%RAML 1.0
title: My API With Types
types:
Person:
properties:
name:
required: true
type: string
age:
required: false
type: number
//: # force all additional properties to be a string
type: string
If a pattern property regular expression also matches an explicitly declared property, the explicitly declared property definition prevails. If two or more pattern property regular expressions match a property name in an instance of the data type, the first one prevails.
Moreover, if additionalProperties
is false
(explicitly or by inheritance) in a given type definition, then explicitly setting pattern properties in that definition is not allowed. If additionalProperties
is true
(or omitted) in a given type definition, then pattern properties are allowed and further restrict the additional properties allowed in that type.
You MAY declare object types that inherit from other object types. A sub-type inherits all the properties of its parent type. In the following example, the type Employee
inherits all properties of its parent type Person
.
#%RAML 1.0
title: My API With Types
types:
Person:
type: object
properties:
name:
type: string
Employee:
type: Person
properties:
id:
type: string
A sub-type MAY override properties of its parent type with the following restrictions: 1) a required property in the parent type cannot be changed to optional in the sub-type, and 2) the type declaration of a defined property in the parent type can only be changed to a narrower type (a specialization of the parent type) in the sub-type.
When payloads contain ambiguous types due to unions or inheritance, it is often impossible to discriminate the concrete type of an individual object at runtime. For example, when deserializing the payload into a statically typed language, this problem can occur.
A RAML processor MAY provide an implementation that automatically selects a concrete type from a set of possible types, but a simpler alternative is to store a unique value associated with the type inside the object.
You MAY set the name of an object property using the discriminator
facet. The name of the object property MAY be used to discriminate the concrete type. You MAY use the discriminatorValue
to store the value that identifies the type of an individual object. By default, the value of discriminatorValue
is the name of the type.
Here's an example that illustrates how to use discriminator
:
#%RAML 1.0
title: My API With Types
types:
Person:
type: object
discriminator: kind # refers to the `kind` property of object `Person`
properties:
kind: string # contains name of the kind of a `Person` instance
name: string
Employee: # kind can equal `Employee`; default value for `discriminatorValue`
type: Person
properties:
employeeId: integer
User: # kind can equal `User`; default value for `discriminatorValue`
type: Person
properties:
userId: integer
data:
- name: A User
userId: 111
kind: User
- name: An Employee
employeeId: 222
kind: Employee
You MAY also override the default for discriminatorValue
for each individual concrete class. The following example replaces the initial capitalization in the default value of discriminatorValue
with lowercase characters:
#%RAML 1.0
title: My API With Types
types:
Person:
type: object
discriminator: kind
properties:
name: string
kind: string
Employee:
type: Person
discriminatorValue: employee # override default
properties:
employeeId: string
User:
type: Person
discriminatorValue: user # override default
properties:
userId: string
data:
- name: A User
userId: 111
kind: user
- name: An Employee
employeeId: 222
kind: employee
discriminator
and discriminatorValue
MUST NOT be defined in any inline type declarations or union types.
# valid whenever there is a key name that can identify a type
types:
Device:
discriminator: kind
properties:
kind: string
# invalid in any inline type declaration
application/json:
discriminator: kind
properties:
kind: string
# invalid for union types
PersonOrDog:
type: Person | Dog
discriminator: hasTail
Array types MUST be declared by using either the array qualifier []
at the end of a type expression or array
as the value of a type
facet. If you are defining a top-level array type, such as the Emails
in the examples below, you MAY declare the following facets in addition to those previously described to further restrict the behavior of the array type.
Facet | Description |
---|---|
uniqueItems? | Boolean value that indicates if items in the array MUST be unique. |
items? | Indicates the type all items in the array are inherited from. Can be a reference to an existing type or an inline type declaration. |
minItems? | Minimum amount of items in array. Value MUST be equal to or greater than 0. Default: 0 . |
maxItems? | Maximum amount of items in array. Value MUST be equal to or greater than 0. Default: 2147483647 . |
Both of the following examples are valid:
types:
Email:
type: object
properties:
subject: string
body: string
Emails:
type: Email[]
minItems: 1
uniqueItems: true
example: # example that contains array
- # start item 1
subject: My Email 1
body: This is the text for email 1.
- # start item 2
subject: My Email 2
body: This is the text for email 2.
types:
Email:
type: object
properties:
name:
type: string
Emails:
type: array
items: Email
minItems: 1
uniqueItems: true
Using Email[]
is equivalent to using type: array
. The items
facet defines the Email
type as the one each array item inherits from.
RAML defines a set of built-in scalar types, each of which has a predefined set of restrictions.
A JSON string with the following additional facets:
Facet | Description |
---|---|
pattern? | Regular expression that this string MUST match. |
minLength? | Minimum length of the string. Value MUST be equal to or greater than 0. Default: 0 |
maxLength? | Maximum length of the string. Value MUST be equal to or greater than 0. Default: 2147483647 |
Example:
types:
EmailAddress:
type: string
pattern: ^.+@.+\..+$
minLength: 3
maxLength: 320
Any JSON number with the following additional facets:
Facet | Description |
---|---|
minimum? | The minimum value. |
maximum? | The maximum value. |
format? | The format of the value. The value MUST be one of the following: int, int8, int16, int32, int64, long, float, double. |
multipleOf? | A numeric instance is valid against "multipleOf" if the result of dividing the instance by this keyword's value is an integer. |
Example:
types:
Weight:
type: number
minimum: -1.1
maximum: 20.9
format: float
multipleOf: 1.1
Any JSON number that is a positive or negative multiple of 1. The integer type inherits its facets from the number type.
types:
Age:
type: integer
minimum: -3
maximum: 5
format: int8
A JSON boolean without any additional facets.
types:
IsMarried:
type: boolean
The following date type representations MUST be supported:
Type | Description |
---|---|
date-only | The "full-date" notation of RFC3339, namely yyyy-mm-dd . Does not support time or time zone-offset notation. |
time-only | The "partial-time" notation of RFC3339, namely hh:mm:ss[.ff...]. Does not support date or time zone-offset notation. |
datetime-only | Combined date-only and time-only with a separator of "T", namely yyyy-mm-ddThh:mm:ss[.ff...]. Does not support a time zone offset. |
datetime | A timestamp in one of the following formats: if the format is omitted or set to rfc3339 , uses the "date-time" notation of RFC3339; if format is set to rfc2616 , uses the format defined in RFC2616. |
The additional facet format
MUST be available only when the type equals datetime
:
Facet | Description |
---|---|
format? | The format of the value of a type datetime . The value MUST be either rfc3339 or rfc2616 . Any other values are invalid. |
types:
birthday:
type: date-only # no implications about time or offset
example: 2015-05-23
lunchtime:
type: time-only # no implications about date or offset
example: 12:30:00
fireworks:
type: datetime-only # no implications about offset
example: 2015-07-04T21:00:00
created:
type: datetime
example: 2016-02-28T16:41:41.090Z
format: rfc3339 # the default, so no need to specify
If-Modified-Since:
type: datetime
example: Sun, 28 Feb 2016 16:41:41 GMT
format: rfc2616 # this time it's required, otherwise, the example format is invalid
The file type can constrain the content to send through forms. When this type is used in the context of web forms it SHOULD be represented as a valid file upload in JSON format. File content SHOULD be a base64-encoded string.
Facet | Description |
---|---|
fileTypes? | A list of valid content-type strings for the file. The file type */* MUST be a valid value. |
minLength? | Specifies the minimum number of bytes for a parameter value. The value MUST be equal to or greater than 0. Default: 0 |
maxLength? | Specifies the maximum number of bytes for a parameter value. The value MUST be equal to or greater than 0. Default: 2147483647 |
types:
userPicture:
type: file
fileTypes: ['image/jpeg', 'image/png']
maxLength: 307200
customFile:
type: file
fileTypes: ['*/*'] # any file type allowed
maxLength: 1048576
In RAML, the type nil
is a scalar type that SHALL allow only nil data values. Specifically, in YAML, it allows only YAML's null
(or its equivalent representations, such as ~
). In JSON, it allows only JSON's null
, and in XML, it allows only XML's xsi:nil
. In headers, URI parameters, and query parameters, the nil
type SHALL only allow the string value "nil" (case-sensitive); and in turn, an instance having the string value "nil" (case-sensitive), when described with the nil
type, SHALL deserialize to a nil value.
Using the type nil
in a union makes a type definition nilable, which means that any instance of that union MAY be a nil data value. When such a union is composed of only one type in addition to | nil
, use of a trailing question mark ?
instead of the union syntax is equivalent. The use of that equivalent, alternative syntax SHALL be restricted to scalar types and references to user-defined types, and SHALL NOT be used in type expressions.
In the following example, the type is an object and has two required properties, name
and comment
, both defaulting to type string
. In example
, name
is assigned a string value, but comment is nil and this is not allowed because RAML expects a string.
types:
NilValue:
type: object
properties:
name:
comment:
example:
name: Fred
comment: # Providing no value here is not allowed.
The following example shows the assignment of the nil
type to comment
:
types:
NilValue:
type: object
properties:
name:
comment: nil
example:
name: Fred
comment: # Providing a value here is not allowed.
The following example shows how to represent nilable properties using a union:
types:
NilValue:
type: object
properties:
name:
comment: nil | string # equivalent to ->
# comment: string?
example:
name: Fred
comment: # Providing a value or not providing a value here is allowed.
Declaring the type of a property to be nil
represents the lack of a value in a type instance. In a RAML context that requires values of type nil
(vs just type declarations), the usual YAML null
is used, e.g. when the type is nil | number
you may use enum: [ 1, 2, ~ ]
or more explicitly/verbosely enum: [ 1, 2, !!null "" ]
; in non-inline notation you can just omit the value completely, of course.
Nilable values are not the same as optional properties. For example, you can define a comment
property that is optional and that accepts a nil
value by using the syntax comment?: string?
or comment?: nil | string
.
A union type MAY be used to allow instances of data to be described by any of several types. A union type MUST be declared via a type expression that combines 2 or more types delimited by pipe (|
) symbols; these combined types are referred to as the union type's super types. In the following example, instances of the Device
type MAY be described by either the Phone
type or the Notebook
type:
#%RAML 1.0
title: My API With Types
types:
Phone:
type: object
properties:
manufacturer:
type: string
numberOfSIMCards:
type: number
kind: string
Notebook:
type: object
properties:
manufacturer:
type: string
numberOfUSBPorts:
type: number
kind: string
Device:
type: Phone | Notebook
An instance of a union type SHALL be considered valid if and only if it meets all restrictions associated with at least one of the super types. More generally, an instance of a type that has a union type in its type hierarchy SHALL be considered valid if and only if it is a valid instance of at least one of the super types obtained by expanding all unions in that type hierarchy. Such an instance is deserialized by performing this expansion and then matching the instance against all the super types, starting from the left-most and proceeding to the right; the first successfully-matching base type is used to deserialize the instance.
The following example defines two types and a third type which is a union of those two types.
types:
CatOrDog:
type: Cat | Dog # elements: Cat or Dog
Cat:
type: object
properties:
name: string
color: string
Dog:
type: object
properties:
name: string
fangs: string
The following example of an instance of type CatOrDog
is valid:
CatOrDog: # follows restrictions applied to the type 'Cat'
name: Musia,
color: brown
Imagine a more complex example of a union type used in a multiple inheritance type expression:
types:
HasHome:
type: object
properties:
homeAddress: string
Cat:
type: object
properties:
name: string
color: string
Dog:
type: object
properties:
name: string
fangs: string
HomeAnimal: [ HasHome , Dog | Cat ]
In this case, type HomeAnimal
has two super types, HasHome
and an anonymous union type, defined by the following type expression: Dog | Cat
.
Validating the HomeAnimal
type involves validating the types derived from each of the super types and the types of each element in the union type. In this particular case, the processor MUST test that types [HasHome, Dog]
and [HasHome, Cat]
are valid types.
If you are extending from two union types a processor MUST perform validations for every possible combination. For example, to validate the HomeAnimal
type shown below, the processor MUST test the six possible combinations: [HasHome, Dog ]
, [HasHome, Cat ]
, [HasHome, Parrot]
, [IsOnFarm, Dog ]
, [IsOnFarm, Cat ]
, and [IsOnFarm, Parrot]
.
types:
HomeAnimal: [ HasHome | IsOnFarm , Dog | Cat | Parrot ]
If a union type contains a facet with an enum
, every value of that enum
MUST meet all restrictions associated with at least one of the super types. Here is an example:
The following example illustrates a valid expression:
type: number | boolean
enum: [1, true, 2]
The following example illustrates an invalid expression:
type: number | boolean
enum: [1, true, 2, "hello"]
Note that types, in this case, can be built-in data types, such as numbers or boolean, or can be custom user-defined types, such as unions or complex types with multiple properties. Imagine a more complex example:
#%RAML 1.0
title: Scheduling API
types:
CustomDates:
enum: [Monday12, Tuesday18, Wednesday7]
PossibleMeetingDates:
properties:
daysAllowed:
type: CustomDates | date-only
enum: [Monday12, Wednesday7, 2020-02-08, 2020-02-09]
PossibleVacationDates:
properties:
daysAllowed:
type: datetime-only
enum: [2020-02-01T00:00:00, 2019-02-22T00:00:00]
ScheduledDays:
type: PossibleMeetingDates | PossibleVacationDates
properties:
daysAllowed:
enum: [2020-02-01T00:00:00, Monday12] # VALID
# enum: [Tuesday123] # INVALID: "Tuesday123" does not match any of the super-types' enum values
# enum: [Tuesday18] # INVALID: although "Tuesday18" is an (allowed) enum value of "CustomDates", it is not listed in "PossibleMeetingDates" > "daysAllowed" `enum`, which is more restrictive
# enum: [2020-02-01T00:00:00, 2020-02-18] # INVALID
A union type MAY use facets defined by any of its member types as long as all member types in the union accept those facets, for example:
types:
Foo: number
Bar: integer
FooBar:
type: Foo | Bar
minimum: 1 # valid because both "Foo" (number) and "Bar" (integer) all accept "minimum"
types:
Foo: number
Bar: integer
Qux: string
FooBarQux:
type: Foo | Bar | Qux
minimum: 1 # invalid because "Qux" (string) does not accept the "minimum" facet
types:
Foo: number
Bar: integer
Qux:
type: string
facets:
minimum: number
FooBarQux:
type: Foo | Bar | Qux
minimum: 1 # valid because "Qux" (string) has a user-defined facet "minimum"
RAML allows the use of XML and JSON schemas to describe the body of an API request or response by integrating the schemas into its data type system.
The following examples show how to include an external JSON schema into a root-level type definition and a body declaration.
types:
Person: !include person.json
/people/{personId}:
get:
responses:
200:
body:
application/json:
type: !include person.json
A RAML processor MUST NOT allow types that define an XML or JSON schema to participate in type inheritance or specialization, or effectively in any type expression. Therefore, you SHALL NOT define sub-types of these types to declare new properties, add restrictions, set facets, or declare facets. You MAY, however, create simple type wrappers that add annotations, examples, a display name, or a description.
The following example shows a valid declaration.
types:
Person:
type: !include person.json
description: this is a schema describing a person
The following example shows an invalid declaration of a type that inherits the characteristics of a JSON schema and adds additional properties.
types:
Person:
type: !include person.json
properties: # invalid
single: boolean
Another invalid case is shown in the following example of the type Person
being used as a property type.
types:
Person:
type: !include person.json
description: this is a schema describing a person
Board:
properties:
members: Person[] # invalid use of type expression '[]' and as a property type
A RAML processor MUST be able to interpret and apply JSON and XML schemas.
Because JSON is also a valid YAML 1.2 syntax, a RAML processor SHOULD interpret JSON-formatted data structures that do not contain a $schema
key as RAML type declarations.
An XML schema, or JSON schema, MUST NOT be used where the media type does not allow XML-formatted data, or JSON-formatted data, respectively. XML and JSON schemas are also forbidden in any declaration of query parameters, query string, URI parameters, and headers.
The nodes "schemas" and "types", as well as "schema" and "type", are mutually exclusive and synonymous for compatibility with RAML 0.8. API definitions SHOULD use "types" and "type", as "schemas" and "schema" are deprecated and might be removed in a future RAML version.
You MAY refer to an element defined in a schema. RAML supports that by using URL fragments as shown in the example below.
type: !include elements.xsd#Foo
When referencing an inner element of a JSON or XML schema, a RAML processor MUST validate an instance against that element. The RAML specification supports referencing any inner elements in JSON schemas that are valid schemas, any globally defined elements, and complex types in XML schemas. There are a few restrictions:
- Validation of any XML or JSON instance against inner elements MUST follow the same restrictions as the validation against a regular XML or JSON schema.
- Referencing complex types inside an XML schema is valid for determining the structure of an XML instance. However, because complex types do not define a name for the top-level XML element, these types SHALL NOT be used for serializing an XML instance.
- References pointing to inner elements of JSON schemas MUST be valid JSON Pointers as defined in RFC6901.
Facets express various additional restrictions beyond those which types impose on their instances, such as the optional minimum
and maximum
facets for numbers, or the enum
facet for scalars. In addition to the built-in facets, RAML provides a way to declare user-defined facets for any data type.
The user-defined facet is declared using the OPTIONAL facets
facet in a type declaration. The value of the facets
facet MUST be a map. The key names the user-defined facet. The corresponding value defines the concrete value that the respective facet can take. The syntax of a property declaration and a user-defined facet declaration are the same. A facet restricts instances of a sub-type, not its type, based on the concrete value defined in the facet declaration.
Facet names MUST NOT begin with open parenthesis, to disambiguate the names from annotations. User-defined facet names on a type MUST NOT match built-in facets on that type, nor facet names of any ancestor type in the inheritance chain of the type.
If a facet of a type is declared as required, then any subtype of that type MUST define a value for that facet.
Here is an example that defines the capability to restrict dates to those that do not fall on holidays:
#%RAML 1.0
title: API with Types
types:
CustomDate:
type: date-only
facets:
onlyFutureDates?: boolean # optional in `PossibleMeetingDate`
noHolidays: boolean # required in `PossibleMeetingDate`
PossibleMeetingDate:
type: CustomDate
noHolidays: true
In this example, declaring the noHolidays
facet and defining its values to be boolean makes it possible to restrict date instances that fall on holidays. Instances of any inheriting type, such as the PossibleMeetingDate
type, must have values that do not fall on holidays.
By definition, user-defined facets are not built into this RAML specification, and therefore, their semantics might not be understood by all RAML processors. Consequently, a RAML processor MAY (or may not) choose to use user-defined facets on a type in validating instances of that type. In the example above, a RAML processor may or may not assign a meaning to noHolidays
, and therefore, may choose to ignore the noHolidays: true
value in validating instances of PossibleMeetingDate
.
A RAML processor MUST be able to determine the default type of a type declaration by using the following rules:
- If, and only if, a type declaration contains a facet that is unique to that type, its default type is then inferred to be the only one with support for the facet being used.
For example, if a type declaration contains a properties
facet, its default type is object
. The following snippet exemplifies this rule:
types:
Person:
# default type is "object" because "properties" is unique to that type
# i.e. no need to explicitly define it, "type: object" is inferred
properties:
- If, and only if, a type declaration contains a facet that is neither unique to a given type, as described in the previous rule above, nor a
type
orschema
facet, then the default type isstring
. The following snippet exemplifies this rule:
types:
Person:
properties:
name: # no type or schema necessary since the default type is `string`
- The default type
any
is applied to anybody
node that does not containproperties
,type
, orschema
. For example:
body:
application/json:
# default type is `any`
Or, if a default media type has been defined, no need to declare it here:
body:
# default type is `any`
Of course, each rule can be overridden by explicitly defining a type. For example:
types:
Person:
properties:
name:
type: number
Type expressions provide a powerful way of referring to, and even defining, types. Type expressions MAY be used wherever a type is expected. The simplest type expression is the name of a type. Using type expressions, you MAY devise type unions, arrays, maps, and other things.
Expression | Description |
---|---|
Person |
The simplest type expression: A single type |
Person[] |
An array of Person objects |
string[] |
An array of string scalars |
string[][] |
A bi-dimensional array of string scalars |
string | Person |
A union type made of members of string OR Person |
(string | Person)[] |
An array of the type shown above |
Type expressions can be used wherever a type is expected:
#%RAML 1.0
title: My API With Types
types:
Phone:
type: object
properties:
manufacturer:
type: string
numberOfSIMCards:
type: number
Notebook:
type: object
properties:
manufacturer:
type: string
numberOfUSBPorts:
type: number
Person:
type: object
properties:
devices: ( Phone | Notebook )[]
reports: Person[]
You can even "extend" from a type expression. For example:
#%RAML 1.0
title: My API With Types
types:
Phone:
type: object
properties:
manufacturer:
type: string
numberOfSIMCards:
type: number
Notebook:
type: object
properties:
manufacturer:
type: string
numberOfUSBPorts:
type: number
Devices:
type: ( Phone | Notebook )[]
This example is actually declaring a "type alias", which gives a more readable name ( Devices ) to a type defined using a complex type expression. In this case, the type expression consists of an array of a union of the types Phone and Notebook. You can use this technique to give simple names to complex types. Type aliases can also hold extra properties, for example a description and annotations.
Type expressions are composed of names of built-in or custom types and certain symbols, as follows:
Expression Components | Description | Examples |
---|---|---|
type name |
A type name, the basic building block of a type expression, used alone creates the simplest expression. | number: a built-in typePerson: a custom type |
(type expression) |
Parentheses disambiguate the expression to which an operator applies. | Person | Animal[] ( Person | Animal )[] |
(type expression)[] |
The array, a unary, postfix operator placed after another type expression, enclosed in parentheses as needed, indicates the resulting type is an array of instances of that type expression. | string[]: an array of stringsPerson[][]: an array of arrays of Person instances |
(type expression 1) | (type expression 2) |
An infix union operator indicates the resulting type might be either of type expression 1 or of type expression 2. Multiple union operators can be combined between pairs of type expressions. | string | number: either a string or a number X | Y | Z : either an X or a Y or a Z (Manager | Admin)[]: an array whose members consist of Manager or Admin instancesManager[] | Admin[]: an array of Manager instances or an array of Admin instances. |
RAML Types support multiple inheritance. This is achieved by passing a sequence of types:
types:
Person:
type: object
properties:
name: string
Employee:
type: object
properties:
employeeNr: integer
Teacher:
type: [ Person, Employee ]
In the example above, the type Teacher
inherits all restrictions from Person
and Employee
.
Multiple inheritance SHALL be allowed only if the sub-type is still a valid type declaration after inheriting all restrictions from its parent types. Also, it SHALL not be allowed to inherit from different kind of primitive types, for example [ number, string ]
.
In the following example, the sub-type Number3
is fully valid:
types:
Number1:
type: number
minimum: 4
Number2:
type: number
maximum: 10
Number3: [ Number1, Number2]
Whereas using the same example and only changing the maximum value of type Number2
from 10 to 2 would result in an invalid type Number3
.
types:
Number1:
type: number
minimum: 4
Number2:
type: number
maximum: 2
Number3: [ Number1, Number2] # invalid, maximum value cannot be less than minimum value
Section union types illustrates another example of how to validate types that use multiple inheritance and union types.
If a sub-type inherits properties having the same name from at least two of its parent types, the sub-type SHALL keep all restrictions applied to those properties with two exceptions: 1) a pattern
facet when a parent type already declares a pattern
facet 2) a user-defined facet when another user-defined facet has the same value. In these cases, an invalid type declaration occurs.
You MAY declare inline/anonymous types everywhere a type can be referenced except in a Type Expression.
#%RAML 1.0
title: My API With Types
/users/{id}:
get:
responses:
200:
body:
application/json:
type: object
properties:
firstname:
type: string
lastname:
type: string
age:
type: number
It is highly RECOMMENDED that API documentation include a rich selection of examples. RAML supports either the definition of multiple examples or a single one for any given instance of a type declaration. In addition to supporting YAML by default, processors SHOULD support JSON and XML representations of examples. Processors MAY support additional formats. Note that type definition is agnostic to example encoding, so examples in YAML will work for JSON or XML, and vice versa, for any chosen combination of those three supported encodings.
The OPTIONAL examples facet MAY be used to attach multiple examples to a type declaration. Its value MUST be a map of key-value pairs, where each key represents a unique identifier for an example and the value is a single example.
The following example shows the value of an examples facet:
message: # {key} - unique id
# example declaration
title: Attention needed
body: You have been added to group 274
record: # {key} - unique id
# example declaration
name: log item
comment: permission check
The OPTIONAL example facet MAY be used to attach an example of a type instance to the type declaration. There are two ways to represent the example facet value: as an explicit description of a specific type instance, or as a map that contains additional facets.
For example:
title: Attention needed
body: You have been added to group 274
The map MAY contain the following additional facets:
Facet | Description |
---|---|
displayName? | An alternate, human-friendly name for the example. If the example is part of an examples node, the default value is the unique identifier that is defined for this example. |
description? | A substantial, human-friendly description for an example. Its value MUST be a string and MAY be formatted using Markdown. |
(<annotationName>)? | Annotations to be applied to this API. An annotation MUST be a map having a key that begins with "(" and ends with ")", where the text enclosed in parentheses is the annotation name and the value is an instance of that annotation. |
value | The actual example of a type instance. |
strict? | Validates the example against any type declaration (the default), or not. Set this facet to false to avoid validation. |
For example:
(pii): true
strict: false
value:
title: Attention needed
body: You have been added to group 274
The following snippet illustrates the usage of example and examples properties at different levels of a RAML API:
#%RAML 1.0
title: API with Examples
types:
User:
type: object
properties:
name: string
lastname: string
example:
name: Bob
lastname: Marley
Org:
type: object
properties:
name: string
address?: string
value?: string
/organizations:
post:
headers:
UserID:
description: the identifier for the user who posts a new organization
type: string
example: SWED-123 # single scalar example
body:
application/json:
type: Org
example: # single request body example
value: