Intro To RAML - The RESTful API Modeling Language - Baeldung
Intro To RAML - The RESTful API Modeling Language - Baeldung
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!
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.
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).
#%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
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
2.4. Resources
Now, well de ne the top-level resource (URI) of our API:
1
/foos:
/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:
/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.
/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" }
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 }
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
...
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
#%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
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 Workbench (http://apiworkbench.com/) an IDE for designing, building, testing, and documenting
RESTful APIs that supports both RAML 0.8 and 1.0
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.
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.
12Comments
Baeldungblog
Recommend
Share
Login
SortbyBest
Jointhediscussion
Srinathamonthago
Thisarticleisveryuseful.!
IsearchedmanyblogsaboutRAML.ButthisbloggivesmebetterideaaboutRAML.Prettyeasywayofexplainingthingsmakesthisarticle
BEST.!
Reply Share
EugenParaschiv
TheguysbehindRAMLhelpedalottoputtheseriestogethershoutouttoChristian(fromMulesoft)forallthebehindthescenework.
Gladyou'reenjoyingit.Cheers,
Eugen.
Reply Share
sivakkannanmuthukumar2monthsago
Thisisanexcellentone.THANKYOU.Thishasverycleandescriptionsalongwithperfectsyntax.
Reply Share
EugenParaschiv
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
GladyoufoundthewriteuphelpfulVatsav.
Reply Share
TimurYarosh7monthsago
DoyouknowanyusefultoolwithsupportofRAML1.0?I'vefoundthatprojectspageatraml.orgcontainsalotofdeprecatedapplicationswhich
supportonly0.8version.It'ssadbutalotoftoolsstilldon'thavesupportoflatestversionofRAML.Myownlisthere
http://stackoverflow.com/quest...
Reply Share
EugenParaschiv
RAML1.0isstillverynew(onlyafewmonthsoldifI'mnotmistaken)andtheRAMLecosystemprobablyisn'tasstrongasfor
exampleSwagger.Soyeah,it'sverylikelythatit'sgoingtotakeagoodfewmonthsuntil1.0supportpropagates.
Reply Share
TimurYarosh7monthsago
Givepleaseanexampleofexternalizedtype'sramlfile.
Reply Share
EugenParaschiv
HeyTimurthisisn'tactuallyoneofmine(noticetheauthor).I'llpassitontotheauthorandmaybewe'lldoafullarticleonit.Cheers,
Eugen.
Reply Share
AlejandroVentura9monthsago
Thanksforexplanation,itisprettyuseful!
Reply Share
EugenParaschiv
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
Email Address
Download
http://www.baeldung.com/ramlrestfulapimodelinglanguagetutorial
10/10