API fragments with RAML

When defining API specs with RAML, the fact that we define all the information in just one RAML file will make it difficult to maintain and there will be parts and data types that are used over and over again in many different requests URI, such definition is not best practice. Breaking the definition of these reused parts into fragments in other RAML files will help us better manage the definition of API specs, avoiding unnecessary repetition. In this tutorial, I will show you how to define API specs with fragments in RAML.

As an example for this tutorial, I will use a RAML file that defines API specs used to manage student information with the following initial content:

As you can see, all information about the Student object, examples are declared in the same RAML file. Suppose later my application is extended to add additional requests URI to delete and edit classes, get student information of a class:

then as you can see: the content of this RAML file will swell more making it difficult to edit, the examples are not reusable, … Using fragments will help us to solve these inadequacies.

To use fragments, what you need to do is split our RAML file (I will call this RAML file the root RAML file!) by defining fragments for the data types, common information between requests URI using other RAML files, and then declare to use these RAML files in the root RAML file using the keyword “!include”.

In our example above, the first thing we can do is define fragments for data type objects in other RAML files.

I will create 2 new files student.raml and class.raml located in the data-types/objects folder:

to define the data type for Student, Class objects.

To define fragment for data types, we need to declare the line “#%RAML 1.0 DataType” at the beginning of each .raml file. For example, the content of student.raml file will be as follows:

In the class.raml file, we will use the “!include” keyword to declare the Student object as follows:

Now in the root RAML file, we don’t need to declare data type objects anymore. We just need to use the keyword “!include”, for example like this:

For examples, we can create an examples directory to contain these examples:

At this point, you can declare an example in the root RAML file, for example as follows:

The content of our RAML root file after using the fragment is left as follows:

Add Comment