Quantcast
Channel: Baeldung
Viewing all articles
Browse latest Browse all 3522

Introduction to RAML – The RESTful API Modeling Language

$
0
0

1. Overview

In this article, we introduce the RESTful API Modeling Language (RAML), a vendor-neutral, open-specification language built on YAML 1.2 and JSON for describing RESTful APIs.

We’ll cover basic RAML 1.0 syntax and file structure as we demonstrate how to define a simple JSON-based API. We’ll also show how to simplify RAML file maintenance through the use of includes. And if you have legacy APIs that use JSON schema, we’ll show how to incorporate schemas into RAML.

Then we’ll introduce a handful of tools that can enhance your journey into RAML, including authoring tools, documentation generators, and others.

Finally we’ll wrap up by describing the current state of the RAML specification.

2. Defining Your API (creating the .raml file)

The API we’ll define is fairly simple: given the entity types Foo, define basic CRUD operations and a couple of query operations. Here are the resources that we will define for our API:

  • GET /api/v1/foos
  • POST /api/v1/foos
  • GET /api/v1/foos/{id}
  • PUT /api/v1/foos/{id}
  • DELETE /api/v1/foos/{id}
  • GET /api/v1/foos/name/{name}
  • GET /api/v1/foos?name={name}&ownerName={ownerName}

And let’s define our API to be stateless, using HTTP Basic authentication, and to be delivered encrypted over HTTPS. Finally, let’s choose JSON for our data transport format (XML is also supported).

2.1. Root-Level Settings

We’ll start by creating a simple text file named api.raml (the .raml prefix is recommended; the name is arbitrary) and add the RAML version header on line one. At the root level of the file, we define settings that apply to the entire API:

#%RAML 1.0
title: Baeldung Foo REST Services API using Data Types
version: v1
protocols: [ HTTPS ] 
baseUri: http://myapi.mysite.com/api/{version}
mediaType: application/json

Notice on line 3 the use of braces { } around the word “version“. This is how we tell RAML that “version” refers to a property and is to be expanded. Therefore the actual baseUri will be: http://myapi.mysite.com/v1

[Note: the version property is optional and need not be a part of the baseUri.]

2.2. Security

Security is also defined at the root level of the .raml file. So let’s add our HTTP basic security scheme definition:

securitySchemes:
  - basicAuth:
      description: Each request must contain the headers necessary for
                   basic authentication
      type: Basic Authentication
      describedBy:
        headers:
          Authorization:
            description: Used to send the Base64-encoded "username:password"
                         credentials
            type: string
        responses:
          401:
            description: |
              Unauthorized. Either the provided username and password
              combination is invalid, or the user is not allowed to access
              the content provided by the requested URL.

2.3. Data Types

Next, we will define the data types that our API will use:

types:
  Foo:
    type: object
    properties:
      id:
        required: true
        type: integer
      name:
        required: true
        type: string
      ownerName:
        required: false
        type: string

The above example uses expanded syntax for defining our data types. RAML provides some syntactical shortcuts to make our type definitions less verbose. Here is the equivalent data types section using these shortcuts:

types:
  Foo:
    properties:
      id: integer
      name: string
      ownerName?: string
  Error:
    properties:
      code: integer
      message: string

The ‘?’ character following a property name declares that the property is not required.

2.4. Resources

Now, we’ll define the top-level resource (URI) of our API:

/foos:

2.5. URI Parameters

Next, we’ll expand the list of resources, building from our top-level resource:

/foos:
  /{id}:
  /name/{name}:

Here, the braces { } around property names define URI parameters. They represent placeholders in each URI and do not reference root-level RAML file properties as we saw above in the baseUri declaration. The added lines represent the resources /foos/{id} and /foos/name/{name}.

2.6. Methods

The next step is to define the HTTP methods that apply to each resource:

/foos:
  get:
  post:
  /{id}:
    get:
    put:
    delete:
  /name/{name}:
    get:

2.7. Query Parameters

Now we’ll define a way to query the foos collection using query parameters. Note that query parameters are defined using the same syntax that we used above for data types:

/foos:
  get:
    description: List all Foos matching query criteria, if provided;
                 otherwise list all Foos
    queryParameters:
      name?: string
      ownerName?: string

2.8. Responses

Now that we have defined all of the resources for our API, including URI parameters, HTTP methods, and query parameters, it is time to define the expected responses and status codes. Response formats are typically defined in terms of data types and examples.

JSON schema can be used in lieu of data types for backward compatibility with an earlier version of RAML. We will introduce JSON schema in section 3.

[Note: In the code snippets below, a line containing only three dots (…) indicates that some lines are being skipped for brevity.]

Let’s start with the simple GET operation on /foos/{id}:

/foos:
  ...
  /{id}:
    get:
      description: Get a Foo by id
      responses:
        200:
          body:
            application/json:
              type: Foo
              example: { "id" : 1, "name" : "First Foo" }

This example shows that by performing a GET request on the resource /foos/{id}, we should get back the matching Foo in the form of a JSON object and an HTTP status code of 200.

Here is how we would define the GET request on the /foos resource:

/foos:
  get:
    description: List all Foos matching query criteria, if provided;
                 otherwise list all Foos
    queryParameters:
      name?: string
      ownerName?: string
    responses:
      200:
        body:
          application/json:
            type: Foo[]
            example: |
              [
                { "id" : 1, "name" : "First Foo" },
                { "id" : 2, "name" : "Second Foo" }
              ]

Note the use of square brackets [] appended to the Foo type. This demonstrates how we would define a response body containing an array of Foo objects, with the example being an array of JSON objects.

2.9. Request Body

Next we will define the request bodies that correspond to each POST and PUT request. Let’s begin with creating a new Foo object:

/foos:
  ...
  post:
    description: Create a new Foo
    body:
      application/json:
        type: Foo
        example: { "id" : 5, "name" : "Another foo" }
    responses:
      201:
        body:
          application/json:
            type: Foo
            example: { "id" : 5, "name" : "Another foo" }

2.10. Status Codes

Note in the above example that when creating a new object, we return an HTTP status of 201. The PUT operation for updating an object will return an HTTP status of 200, utilizing the same request and response bodies as the POST operation.

In addition to the expected responses and status codes that we return when a request is successful, we can define the kind of response and status code to expect when an error occurs.

Let’s see how we would define the expected response for the GET request on the /foos/{id} resource when no resource is found with the given id:

        404:
          body:
            application/json:
              type: Error
              example: { "message" : "Not found", "code" : 1001 }

3. RAML with JSON Schema

Before data types were introduced in RAML 1.0, objects, request bodies, and response bodies were defined using JSON Schema. And while it is still supported in RAML 1.0, the use of JSON schema may be deprecated in a future version.

Here is how you would define the Foo object type at the root level of the .raml file using JSON schema:

schemas:
  - foo: |
      { "$schema": "http://json-schema.org/schema",
         "type": "object",
         "description": "Foo details",
         "properties": {
           "id": { "type": integer },
           "name": { "type": "string" },
           "ownerName": { "type": "string" }
         },
         "required": [ "id", "name" ]
      }

And here is how you would reference the schema in the GET /foos/{id} resource definition:

/foos:
  ...
  /{id}:
    get:
      description: Get a Foo by its id
      responses:
        200:
          body:
            application/json:
              schema: foo
              ...

4. Refactoring with Includes

As you can see from the above sections, our API is getting rather verbose and repetitive. The RAML specification provides an include mechanism that allows us to externalize repeated and/or lengthy sections of code. We can refactor our API definition using includes, making it more concise and less likely to contain the types of errors that result from the “copy/paste/fix everywhere” methodology.

For example, we can put the data type for a Foo object in the file types/Foo.raml and the type for an Error object in types/Error.raml. Then our types section would look like this:

types:
  Foo: !include types/Foo.raml
  Error: !include types/Error.raml

And if we use JSON schema instead, our schemas section might look like this:

schemas:
  - foo: !include schemas/foo.json
  - error: !include schemas/error.json

5. Completing the API

After externalizing all of the data types and examples to their own files, we can refactor our API using the include facility:

#%RAML 1.0
title: Baeldung Foo REST Services API
version: v1
protocols: [ HTTPS ]
baseUri: http://rest-api.baeldung.com/api/{version}
mediaType: application/json
securedBy: basicAuth
securitySchemes:
  - basicAuth:
      description: Each request must contain the headers necessary for
                   basic authentication
      type: Basic Authentication
      describedBy:
        headers:
          Authorization:
            description: Used to send the Base64 encoded "username:password"
                         credentials
            type: string
        responses:
          401:
            description: |
              Unauthorized. Either the provided username and password
              combination is invalid, or the user is not allowed to access
              the content provided by the requested URL.
types:
  Foo:   !include types/Foo.raml
  Error: !include types/Error.raml
/foos:
  get:
    description: List all Foos matching query criteria, if provided;
                 otherwise list all Foos
    queryParameters:
      name?: string
      ownerName?: string
    responses:
      200:
        body:
          application/json:
            type: Foo[]
            example: !include examples/Foos.json
  post:
    description: Create a new Foo
    body:
      application/json:
        type: Foo
        example: !include examples/Foo.json
    responses:
      201:
        body:
          application/json:
            type: Foo
            example: !include examples/Foo.json
  /{id}:
    get:
      description: Get a Foo by id
      responses:
        200:
          body:
            application/json:
              type: Foo
              example: !include examples/Foo.json
        404:
          body:
            application/json:
              type: Error
              example: !include examples/Error.json
    put:
      description: Update a Foo by id
      body:
        application/json:
          type: Foo
          example: !include examples/Foo.json
      responses:
        200:
          body:
            application/json:
              type: Foo
              example: !include examples/Foo.json
        404:
          body:
            application/json:
              type: Error
              example: !include examples/Error.json
    delete:
      description: Delete a Foo by id
      responses:
        204:
        404:
          body:
            application/json:
              type: Error
              example: !include examples/Error.json
  /name/{name}:
    get:
      description: List all Foos with a certain name
      responses:
        200:
          body:
            application/json:
              type: Foo[]
              example: !include examples/Foos.json

6. RAML Tools

One of the great things about RAML is the tool support. There are tools for parsing, validating, and authoring RAML APIs; tools for client code generation; tools for generating API documentation in HTML and PDF formats; and tools that assist you with testing against a RAML API specification. There is even a tool that will convert a Swagger JSON API into RAML.

Here is a sampling of available tools:

  • API Designer – a web-based tool geared towards rapid and efficient API design
  • API Workbench – an IDE for designing, building, testing, and documenting RESTful APIs that supports both RAML 0.8 and 1.0
  • RAML Cop – a tool for validating RAML files
  • RAML for JAX-RS – a set of tools for generating a skeleton of Java + JAX-RS application code from a RAML spec, or for generating a RAML spec from an existing JAX-RS application
  • RAML Sublime Plugin – a syntax highlighter plugin for the Sublime text editor
  • RAML to HTML – a tool for generating HTML documentation from RAML
  • raml2pdf – a tool for generating PDF documentation from RAML
  • RAML2Wiki – a tool for generating Wiki documentation (using Confluence/JIRA markup)
  • SoapUI RAML Plugin – a RAML plugin for the popular SoapUI functional API testing suite
  • Vigia – an integration test suite capable of generating test cases based on a RAML definition

For a complete listing of RAML tools and related projects, visit the RAML Projects page.

7. Current State of RAML

The RAML 1.0 (RC) specification gained release-candidate status on November 3, 2015, and at the time of this writing, version 1.0 was expected to be finalized within the month. Its predecessor, RAML 0.8 was originally released in the Fall of 2014 and is still supported by a myriad of tools.

8. Further Reading

Here are some links that you may find useful along your journey with RAML.

9. Conclusion

This article introduced the RESTful API Modeling Language (RAML). We demonstrated some basic syntax for writing a simple API specification using the RAML 1.0 (RC) spec. And we saw ways to make our definitions more concise by using syntactical shortcuts and externalizing examples, data types, and schemas into ‘include’ files. Then we introduced a collection of powerful tools that work with the RAML spec to assist with everyday API design, development, testing, and documentation tasks.

With the upcoming official release of version 1.0 of the spec, coupled with the overwhelming support of tools developers, it looks like RAML is here to stay.


Viewing all articles
Browse latest Browse all 3522

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>