RAML (RESTful API Modeling Language) Specification

repository·master·Indexed 26 days ago

https://github.com/raml-org/raml-spec

A language for defining HTTP-based APIs that follow REST principles using YAML 1.2. The specification covers API resources, methods, data types, and the generation of client/server code and documentation. This documentation includes details for RAML 1.0 and RAML 0.8, including root section configuration, resource nesting, URI parameters, and the use of the !include tag for external files.

Tokens
26.7K
Snippets
77
Records
96
Agent score
84%

What's inside RAML

  1. Apply Default Security via securedBy

    master

    The securedBy node sets the default security schemes that apply to every method of every resource in the API. The value must be an array of security scheme names defined in the securitySchemes node.

    #%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
  2. Set Default Media Types

    master

    The mediaType node sets the default media type for all request and response bodies. It can be a single string or a sequence of strings. Explicitly defining a mediaType within a specific body (request or response) overrides this default.

    #%RAML 1.0
    title: New API
    mediaType: [ application/json, application/xml ]
    
    /people:
      get:
        responses:
          200:
            body: Person[]
    
    /messages:
      post:
        body:
          application/json:
            type: Another
  3. Define Typed Fragments

    master

    You can create specialized RAML files called 'Typed Fragments' by starting the file with a specific fragment identifier. This allows you to modularize specific parts of your API like data types, traits, or resource types.

    Common Fragment Identifiers:

    • DocumentationItem
    • DataType
    • NamedExample
    • ResourceType
    • Trait
    • AnnotationTypeDeclaration
    • Library
    • Overlay
    • Extension
    • SecurityScheme

    Example of a ResourceType fragment:

    #%RAML 1.0 ResourceType
    
    description: A collection resource
    get:
      description: Retrieve all items
    #%RAML 1.0 ResourceType
    
    description: A collection resource
    usage: Use this to describe a resource that lists items
    get:
      description: Retrieve all items
    post:
      description: Add an item
      responses:
        201:
          headers:
            Location:
  4. Define optional properties in RAML 1.0 types

    master

    In RAML 1.0, you can make a property optional using the ? suffix in the property name.

    Important: If you explicitly specify the required facet in a type declaration, any ? in the property name is treated as part of the literal name rather than an optionality indicator. To make a property with a trailing question mark optional, you must use either required: false or a double question mark ?? suffix.

    Examples:

    • Standard optional property: age?: number
    • Explicitly optional: age: { type: number, required: false }
    • Optional property with a literal question mark in the name: preference??:
    types:
      Person:
        properties:
          name: string
          age?: number
    
      profile:
        properties:
          preference??:
  5. Annotate scalar-valued nodes

    master

    Annotations cannot be directly applied to scalar-valued nodes (like baseUri or version) using standard syntax. To annotate a scalar node, you must use a map-valued syntax where the actual value is assigned to a key named value. This allows you to attach annotations as additional key-value pairs to that map.

    Supported scalar-valued nodes include: displayName, description, type, schema, default, example, usage, required, content, strict, minLength, maxLength, uniqueItems, minItems, maxItems, discriminator, minProperties, maxProperties, discriminatorValue, pattern, format, minimum, maximum, multipleOf, requestTokenUri, authorizationUri, tokenCredentialsUri, accessTokenUri, title, version, baseUri, mediaType, extends.

    baseUri:
      value: http://www.example.com/api
      (redirectable): true
  6. Use Traits to reuse method definitions

    master

    A trait is a partial method definition that provides method-level properties such as description, headers, queryParameters, and responses. Methods inherit these using the is property.

    Traits are declared at the root level under the traits key. A method can use one or more traits, or a resource can apply a list of traits to all its methods using the is property.

    Note: Traits can be applied to all methods of a resource by using the is property at the resource level.

    #%RAML 0.8
    title: Example API
    version: v1
    traits:
      - secured:
          usage: Apply this to any method that needs to be secured
          description: Some requests require authentication.
          queryParameters:
            access_token:
              description: Access Token
              type: string
              example: ACCESS_TOKEN
              required: true
  7. Extend or Overlay an API definition

    master

    RAML provides two ways to modify an existing API definition (the 'master' document):

    1. Overlays: Used to add or override non-behavioral metadata (e.g., title, description, documentation, examples, annotations). Overlays cannot change the functional behavior (resources, methods, parameters, etc.) of the API.
    2. Extensions: Used to broaden or modify the actual behavior of the API (e.g., adding new resources, methods, or changing baseUri).

    Both require a root-level extends node pointing to the master document.

    Overlay Syntax: #%RAML 1.0 Overlay
    Extension Syntax: #%RAML 1.0 Extension

    #%RAML 1.0 Overlay
    usage: Spanish localization
    extends: librarybooks.raml
    documentation:
      - title: Introducción
        content: El acceso automatizado a los libros
    /books:
      description: La colección de libros de la biblioteca
  8. Use optional properties in resource types and traits

    master

    In RAML 0.8, you can define optional properties within a resource type or trait by appending a question mark (?) suffix to a non-scalar property name. This property will only be applied to a resource or method if the corresponding property (without the ?) is already defined at that level.

    Note: This feature is strictly for non-scalar properties. Using the ? suffix on scalar properties like usage or displayName must be rejected by parsers.

    #%RAML 0.8
    title: Example of Optional Properties
    resourceTypes:
      - auditableResource:
          post?:
            body:
              createAuthority:
                description: |
                  If the resource has a post method defined, expect a createAuthority
                  property in its body
          delete?:
            body:
              deleteAuthority:
                description: |
                  If the resource has a delete method defined, expect a deleteAuthority
                  property in its body
  9. Declare user-defined facets in RAML types

    master

    User-defined facets allow you to add custom restrictions to a data type beyond built-in facets (like minimum or enum).

    Rules for declaration:

    • Use the facets facet within a type declaration. The value MUST be a map.
    • The key is the facet name; the value defines the allowed concrete value.
    • Facet names MUST NOT begin with an open parenthesis (.
    • Facet names MUST NOT match built-in facets or facets of ancestor types.
    • If a facet is declared as required, all subtypes MUST define a value for it.
    • Note: Since these are user-defined, a RAML processor MAY choose to ignore them during validation.

    Example: Defining a custom date type that can optionally restrict dates to the future and optionally require they are not 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
  10. Implement object type inheritance (Specialization)

    master

    You can create sub-types that inherit properties from a parent type by setting the type facet of the sub-type to the name of the parent type.

    Restrictions on overriding parent properties:

    1. A required property in a parent type cannot be changed to optional in a sub-type.
    2. A property's type in a sub-type can only be changed to a narrower type (a specialization of the parent type).
    #%RAML 1.0
    title: My API With Types
    types:
      Person:
        type: object
        properties:
          name:
            type: string
      Employee:
        type: Person
        properties:
          id:
            type: string
  11. Apply Resource Types and Traits

    master

    Once declared, you can apply patterns to your API resources and methods:

    • Apply a Resource Type: Use the type node on a resource. The value must be the name of a defined resource type or a type from a library.
    • Apply a Trait: Use the is node.
      • On a method: The value must be an array of trait names. Traits are applied in left-to-right order.
      • On a resource: Applying a trait via is on a resource is equivalent to applying it to all methods of that resource.

    Note: Trait definitions do not apply to nested resources.

    #%RAML 1.0
    title: Example API
    version: v1
    resourceTypes:
      collection:  !include resourceTypes/collection.raml
      member: !include resourceTypes/member.raml
    traits:
      secured:     !include traits/secured.raml
      paged:       !include traits/paged.raml
      rateLimited: !include traits/rate-limited.raml
    /users:
      type: collection
      is: [ secured ]
      get:
        is: [ paged, rateLimited ] # this method is also secured
      post:                        # this method is also secured
  12. Apply security schemes to an API or method

    master

    Apply to entire API

    Use the securedBy attribute at the root level to apply a security scheme to every method in the API.

    Apply to a specific method

    Use the securedBy attribute on a method to override the root-level security. The value must be a list of security schemes defined in securitySchemes.

    Apply to a resource

    Use the securedBy key on a resource to apply the scheme to all methods within that resource.

    Allow anonymous access

    To indicate a method can be called without any security scheme, use null in the securedBy list.

    #%RAML 0.8
    title: GitHub API
    version: v3
    baseUri: https://api.github.com
    securitySchemes:
        - oauth_2_0: !include oauth_2_0.yml
    /users/{userid}/gists:
        get:
            securedBy: [null, oauth_2_0]
            description: | 
                List the authenticated user’s gists or if called anonymously, 
                this will return all public gists.