RAML Datatypes Overview

With RAML 1.0, datatypes has been introduced which makes it easy to describe the data in an API. The declaration of a datatype adds a rule to validate the data. Datatypes are inbuilt 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. 

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 readable than JSON and XML schemas while retaining their flexibility and expressiveness. 

The following snippet shows an examples of type declaration: 

#%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

Check this examples to understand how the data types are used in RAML. In fact, if you come from an object oriented programming it is more relatable to data types in java. 

#%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 of RAML datatypes:

  • 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. So,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.