Saturday, 7 May 2016

RAML Restful API Modeling Language Overview

RAML Version 1.0: RESTful API Modeling Language

Abstract

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.

Status of this Document

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 this version of the RAML specification.

Terminology and Conformance Language

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".

Definitions and Terminology

General

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.
resource is the conceptual mapping to an entity or set of entities.
A trailing question mark, for example description?, indicates an optional property.

Template URI

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.

Markdown

Throughout this specification, Markdown means GitHub-Flavored Markdown.

Introduction

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 and XML Schema.
  • 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.

What's New and Different in RAML 1.0

  • 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 Schema and JSON Schema and even referring to sub-schemas, but in many cases just obviates the schemas
    • Simplifies coding, compared to the JSON Schema or XML Schema, by virtue of being 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

Markup Language

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 are 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 specification-compliant document MUST match the IETF RFC5234 – Augmented BNF for Syntax Specifications:
“#%RAML” SP “1.0” SP [FragmentType] CRLF
The FragmentType is NOT ALLOWED in API definitions and is OPTIONAL for the specification of RAML fragmentdocuments. RAML fragment documents are reusable RAML modules that a larger API definition references or includes.
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 consists of a YAML comment that specifies the RAML version. Therefore, RAML processors cannot completely ignore all YAML comments.
  • The order of some properties at certain levels within a RAML document is significant. Therefore, processors are expected to preserve this ordering.
  • Property names, also known as Keys, at certain levels are not repeatable. Although YAML allows such repetition, the value of a duplicate key, key 2 for example, overwrites the value of the duplicated key 1.

The Root of the Document

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 ]
/search:
  /code:
    type: collection
    get:
The following table enumerates the possible nodes at the root of a RAML document:
NameDescription
titleA 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 nodeis 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.

User Documentation

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 is a sequence of one or more documents. Each document is a map that MUST have exactly two key-value pairs described in following table:
NameDescription
titleTitle of the document. Its value MUST be a non-empty string.
contentContent 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

Base URI and Base URI Parameters

The OPTIONAL baseUri node specifies a URI as an identifier for the API as a whole, and MAY be used the 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 ParameterValue
versionThe 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 structure and semantics 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 (/), those 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 arehttp://api.test.com/common/users and http://api.test.com/common/users/groups.
baseUri: http://api.test.com/common/
/users:
  /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/, and//api.test.com//common//users//groups//.
baseUri: //api.test.com//common//
/:
  /users/:
    /groups//:

Protocols

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 is used; if the protocols node is explicitly specified, the node specification overrides 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 is 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

Default Media Types

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 needs to 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 /list returns a Person[] body represented as either JSON or XML. The resource/send overrides the default media type by explicitly defining an application/json node. Therefore, the resource /sendreturns only a JSON-formatted body.
#%RAML 1.0
title: New API
mediaType: [ application/json, application/xml ]
types:
  Person:
  Another:
/list:
  get:
    responses:
      200:
        body: Person[]
/send:
  post:
    body:
      application/json:
        type: Another

Default Security

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 is 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 Data Types

Introduction

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

Overview

The RAML type system borrows from object oriented programming languages such as Java, as well as from XSD and JSON Schemas.
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.
The following diagram shows the type families and examples of these custom types: an object family member Person and a scalar family member phone.
Types Hierarchy

Defining Types

Types can 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 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

Type Declarations

A type declaration can extend a built-in type or other custom type, or add more information to types, such as specific examples or annotations. Here are the facets that all type declarations can have; certain type declarations might have other facets:
FacetDescription
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?A base 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.
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.

Object Types

All types that have the built-in object type at the root of their inheritance tree can use the following facets in their type declarations:
FacetDescription
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 if an object instance has 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 andusing 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
An object type is created by explicit inheritance from the built-in type object:
#%RAML 1.0
title: My API With Types
types:
  Person:
    type: object
    properties:
      name:
        required: true
        type: string

1 comment: