You are on page 1of 10

11/14/2016

IntrotoRAMLTheRESTfulAPIModelingLanguage|Baeldung

(http://baeldung.com)

Introduction to RAML
The RESTful API Modeling
Language
Last modi ed: October 14, 2016

by
baeldung
(http://www.baeldung.com/author/baeldung/)

REST (HTTP://WWW.BAELDUNG.COM/CATEGORY/REST/)

If you're new here, join the next webinar: "Secure a Spring REST API with OAuth2 + JWT"
(http://www.baeldung.com/webinar). Thanks for visiting!

I just announced the Master Class of my "REST With Spring" Course:


>> THE "REST WITH SPRING" CLASSES (http://www.baeldung.com/rest-with-spring-course?
utm_source=blog&utm_medium=web&utm_content=rest_start&utm_campaign=rws)

1. Overview
In this article, we introduce the RESTful API Modeling Language (RAML) (http://www.raml.org), a vendor-neutral, openspeci cation language built on YAML 1.2 (http://yaml.org/spec/1.2/spec.html) and JSON for describing RESTful APIs.
Well cover basic RAML 1.0 syntax and le structure as we demonstrate how to de ne a simple JSON-based API.Well
also show how tosimplify RAML le maintenance throughthe use ofincludes. And if you have legacy APIs that use
JSON schema, well showhow to incorporateschemas into RAML.
Then well introduce a handful of tools that can enhance your journey into RAML, including authoring tools,
documentation generators, and others.
Finally well wrap up by describing the current state of the RAML speci cation.

2. De ning Your API (creating the .raml le)


The API well de ne is fairly simple: given theentity typesFoo, de ne basic CRUD operations and a couple ofquery
operations. Here are the resources that we will de ne 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}
http://www.baeldung.com/ramlrestfulapimodelinglanguagetutorial

1/10

11/14/2016

IntrotoRAMLTheRESTfulAPIModelingLanguage|Baeldung

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

2.1. Root-Level Settings


Well start by creating a simple text le named api.raml (the .raml pre x is recommended; the name is arbitrary) and add
the RAML version header on line one. At the root level of the le, we de ne settings that apply to the entire API:
1
2
3
4
5
6

#%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 de ned at the root level of the .raml le. So lets add our HTTP basic security scheme de nition:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

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

necessary for

"username:password"

and password
allowed to access

2.3. Data Types


Next, we will de ne the data types that our API will use:
1
2
3
4
5
6
7
8
9
10
11
12
13

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

The above exampleuses expanded syntax for de ning our data types. RAML provides some syntactical shortcuts to
make ourtype de nitions less verbose. Here is the equivalent data types section using these shortcuts:

http://www.baeldung.com/ramlrestfulapimodelinglanguagetutorial

2/10

11/14/2016
1
2
3
4
5
6
7
8
9
10

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

The ? character followinga property namedeclares thatthe property is not required.

2.4. Resources
Now, well de ne the top-level resource (URI) of our API:
1

/foos:

2.5. URI Parameters


Next, well expand the list of resources, building from ourtop-level resource:
1
2
3

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

Here, the braces { } around property names de ne URI parameters. They represent placeholders in each URI and do not
reference root-level RAML le 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 de ne the HTTP methods that apply to each resource:
1
2
3
4
5
6
7
8
9

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

2.7. Query Parameters


Now well de ne a way to query the fooscollection using query parameters. Note that query parameters are de ned
using the same syntax that we used above for data types:
1
2
3
4
5
6
7

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

2.8. Responses

http://www.baeldung.com/ramlrestfulapimodelinglanguagetutorial

3/10

11/14/2016

IntrotoRAMLTheRESTfulAPIModelingLanguage|Baeldung

Now that we have de ned all of the resources for our API, including URI parameters, HTTP methods, and query
parameters, it is time to de ne the expected responses and status codes. Response formats are typically de ned 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.]
Lets start with the simple GET operation on /foos/{id}:
1
2
3
4
5
6
7
8
9
10
11

/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 de ne the GET request on the /foos resource:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

/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 de ne a response body
containing an array of Fooobjects,with the example beingan array of JSON objects.

2.9. Request Body


Next we will de ne the request bodies that correspond to each POST and PUT request. Lets begin with creating a new
Foo object:
1
2
3
4
5
6
7
8
9
10
11
12
13
14

/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


http://www.baeldung.com/ramlrestfulapimodelinglanguagetutorial

4/10

11/14/2016

IntrotoRAMLTheRESTfulAPIModelingLanguage|Baeldung

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 de ne the
kind of response and status code to expect when an error occurs.
Lets see how we would de ne the expected response for the GET request on the /foos/{id} resource when no resource
is found with the given id:
1
2
3
4
5

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 de ned using JSON
Schema. Using data types can be very powerful, but there are cases where you still want to use JSON Schema. In RAML
0.8 you de ned your schemas using the root level schemas section. That is still valid, but it is recommended to use the
types section instead since the use of schemas may be deprecated in a future version. Both types and schemas, as well
as type and schema are synonymous.
Here is how you would de ne the Foo object type at the root level of the .raml le using JSON schema:
1
2
3
4
5
6
7
8
9
10
11
12

types:
foo: |
{ "$schema": "http://json-schema.org/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 ishow you would reference the schemain the GET /foos/{id} resource de nition:
1
2
3
4
5
6
7
8
9
10
11

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

4.Refactoring with Includes


As you can see from the above sections, our API is getting rather verbose and repetitive. The RAML speci cation
provides an include mechanism that allows us to externalize repeated and/or lengthy sections of code. We can refactor
our API de nition using includes, making it more concise and less likely to contain the types of errors that result from
the copy/paste/ x everywhere methodology.
For example, we can put the data type for a Foo object in the le types/Foo.ramland the type for an Error object in
types/Error.raml.Then our types section would look like this:
1
2
3

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

And if we use JSON schema instead, our typessection mightlook like this:
http://www.baeldung.com/ramlrestfulapimodelinglanguagetutorial

5/10

11/14/2016
1
2
3

IntrotoRAMLTheRESTfulAPIModelingLanguage|Baeldung
types:
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 les, we can refactor our API using the include facility:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67

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

http://www.baeldung.com/ramlrestfulapimodelinglanguagetutorial

6/10

11/14/2016

IntrotoRAMLTheRESTfulAPIModelingLanguage|Baeldung

68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101

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 speci cation. There is even a tool that will convert a Swagger JSON API into
RAML.
Here is a sampling of available tools:

API Designer (https://github.com/mulesoft/api-designer) a web-based tool geared towards rapid and


e cient API design

API Workbench (http://apiworkbench.com/) an IDE for designing, building, testing, and documenting
RESTful APIs that supports both RAML 0.8 and 1.0

RAML Cop (https://github.com/thebinarypenguin/raml-cop) a tool for validating RAML les


RAML for JAX-RS (http://View on Github) 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 (https://github.com/mulesoft/raml-sublime-plugin) a syntax highlighter plugin
for the Sublime text editor
RAML to HTML (https://github.com/kevinrenskers/raml2html) a tool for generating HTML
documentation from RAML

raml2pdf (https://github.com/our-bts/raml2pdf) a tool for generating PDF documentation from RAML


RAML2Wiki (https://github.com/jhitchcock/raml2wiki) a tool for generating Wiki documentation (using
Con uence/JIRA markup)

SoapUI RAML Plugin (http://olensmar.blogspot.se/2013/12/a-raml-apihub-plugin-for-soapui.html)


a RAML plugin for the popular SoapUI functional API testing suite
Vigia (https://github.com/nogates/vigia) an integration test suite capable of generating test cases based
on a RAML de nition
For a complete listing of RAML tools and related projects, visit the RAML Projects (http://raml.org/projects/projects)
page.

7. Current State of RAML


http://www.baeldung.com/ramlrestfulapimodelinglanguagetutorial

7/10

11/14/2016

IntrotoRAMLTheRESTfulAPIModelingLanguage|Baeldung

The RAML 1.0 (RC) speci cation gained release-candidate status on November 3, 2015, and at the time of this writing,
version 1.0wasexpected to be nalized withinthe 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 nd useful along your journey with RAML.

RAML.org (http://raml.org/) the o cial site of the RAML speci cation


json-schema.org (http://json-schema.org/) the home of JSON schema
Understanding JSON Schema (http://spacetelescope.github.io/understanding-json-schema/)
JSON Schema Generator (http://jsonschema.net/)
Wikipedia RAML Page (https://en.wikipedia.org/wiki/RAML_(software))

9. Conclusion
This article introduced the RESTful API Modeling Language (RAML). We demonstrated some basic syntax for writing a
simple API speci cation using the RAML 1.0 (RC)spec. And we saw ways to make our de nitions more concise by using
syntactical shortcuts and externalizing examples, data types, and schemas into include les. 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 o cial release of version 1.0 of the spec, coupled with the overwhelming support of tools
developers, it looks like RAML is here to stay.

The Master Class of my "REST With Spring" Course is nally out:


>> CHECK OUT THE CLASSES (http://www.baeldung.com/rest-with-spring-course?
utm_source=blog&utm_medium=web&utm_content=rest_end&utm_campaign=rws)

12Comments

Baeldungblog

Recommend

Share

Login

SortbyBest

Jointhediscussion
Srinathamonthago

Thisarticleisveryuseful.!
IsearchedmanyblogsaboutRAML.ButthisbloggivesmebetterideaaboutRAML.Prettyeasywayofexplainingthingsmakesthisarticle
BEST.!

Reply Share
EugenParaschiv

Mod >Srinath amonthago

TheguysbehindRAMLhelpedalottoputtheseriestogethershoutouttoChristian(fromMulesoft)forallthebehindthescenework.
Gladyou'reenjoyingit.Cheers,
Eugen.

Reply Share
sivakkannanmuthukumar2monthsago

Thisisanexcellentone.THANKYOU.Thishasverycleandescriptionsalongwithperfectsyntax.

Reply Share
EugenParaschiv

Mod >sivakkannanmuthukumar 2monthsago

Surething,I'mgladitwashelpful.TheguysfromRAMLplayedabigpartinkeepingitupdated.
Cheers,
Eugen.

Reply Share
http://www.baeldung.com/ramlrestfulapimodelinglanguagetutorial

8/10

11/14/2016

IntrotoRAMLTheRESTfulAPIModelingLanguage|Baeldung
Vatsav4monthsago

Thisisawesome!Wonderfulwaytoexplainthings.IcanreallystartmyRAMLjourneyfromhere.I'vebeensearchinginternetalotandfinally,
foundthispostveryuseful.

Reply Share
EugenParaschiv

Mod >Vatsav 4monthsago

GladyoufoundthewriteuphelpfulVatsav.

Reply Share
TimurYarosh7monthsago

DoyouknowanyusefultoolwithsupportofRAML1.0?I'vefoundthatprojectspageatraml.orgcontainsalotofdeprecatedapplicationswhich
supportonly0.8version.It'ssadbutalotoftoolsstilldon'thavesupportoflatestversionofRAML.Myownlisthere
http://stackoverflow.com/quest...

Reply Share
EugenParaschiv

Mod >TimurYarosh 7monthsago

RAML1.0isstillverynew(onlyafewmonthsoldifI'mnotmistaken)andtheRAMLecosystemprobablyisn'tasstrongasfor
exampleSwagger.Soyeah,it'sverylikelythatit'sgoingtotakeagoodfewmonthsuntil1.0supportpropagates.

Reply Share
TimurYarosh7monthsago

Givepleaseanexampleofexternalizedtype'sramlfile.

Reply Share
EugenParaschiv

Mod >TimurYarosh 7monthsago

HeyTimurthisisn'tactuallyoneofmine(noticetheauthor).I'llpassitontotheauthorandmaybewe'lldoafullarticleonit.Cheers,
Eugen.

Reply Share
AlejandroVentura9monthsago

Thanksforexplanation,itisprettyuseful!

Reply Share
EugenParaschiv

Mod >AlejandroVentura 9monthsago

Gladyou'refindingitusefulAlejandroRAMLisaprettycooltool.

Reply Share
Subscribe d AddDisqustoyoursiteAddDisqusAdd

Privacy

http://www.baeldung.com/ramlrestfulapimodelinglanguagetutorial

9/10

11/14/2016

IntrotoRAMLTheRESTfulAPIModelingLanguage|Baeldung

CATEGORIES
SPRING (HTTP://WWW.BAELDUNG.COM/CATEGORY/SPRING/)
REST (HTTP://WWW.BAELDUNG.COM/CATEGORY/REST/)
JAVA (HTTP://WWW.BAELDUNG.COM/CATEGORY/JAVA/)
SECURITY (HTTP://WWW.BAELDUNG.COM/CATEGORY/SECURITY-2/)
PERSISTENCE (HTTP://WWW.BAELDUNG.COM/CATEGORY/PERSISTENCE/)
JACKSON (HTTP://WWW.BAELDUNG.COM/CATEGORY/JACKSON/)

Download

Buildinga
REST API with
Spring 4?

HTTPCLIENT (HTTP://WWW.BAELDUNG.COM/CATEGORY/HTTP/)

The E-book

ABOUT

ABOUT BAELDUNG (HTTP://WWW.BAELDUNG.COM/ABOUT/)


THE COURSES (HTTP://COURSES.BAELDUNG.COM)

Email Address

Download

META BAELDUNG (HTTP://META.BAELDUNG.COM/)


THE FULL ARCHIVE (HTTP://WWW.BAELDUNG.COM/FULL_ARCHIVE)
WRITE FOR BAELDUNG (HTTP://WWW.BAELDUNG.COM/CONTRIBUTION-GUIDELINES)
ADVERTISE ON BAELDUNG (HTTPS://WWW.SYNDICATEADS.NET/DIR/BAELDUNG?
UTM_SOURCE=SYNDICATE&UTM_MEDIUM=INPOST&UTM_CAMPAIGN=BAELDUNG)
PRIVACY POLICY (HTTP://WWW.BAELDUNG.COM/PRIVACY-POLICY)
TERMS OF SERVICE (HTTP://WWW.BAELDUNG.COM/TERMS-OF-SERVICE)

http://www.baeldung.com/ramlrestfulapimodelinglanguagetutorial

10/10

You might also like