Trait in RAML is used to define the same elements in different request URIs so that they can be reused. It’s like common class, common method in Java!
For example, I have 2 request URIs with the following definitions:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
#%RAML 1.0 baseUri: https://localhost:8081/api title: RAML Trait version: 1.0 /students/by-name: get: queryParameters: name: string /classes/by-name: get: queryParameters: name: string |
In these two requests, the request parameter “name” is defined the same. Therefore, we can use Trait to define this request parameter and reuse it in 2 requests. When we change the definition for the request parameter “name”, we don’t need to edit many places anymore.
We define the Trait for the request parameter “name” with the name “hasNameParam” as follows:
1 2 3 4 |
traits: hasNameParam: queryParameters: name: string |
And to use it in URI requests, you need to declare it with the “is” keyword as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
#%RAML 1.0 baseUri: https://localhost:8081/api title: RAML Trait version: 1.0 traits: hasNameParam: queryParameters: name: string /students/by-name: get: is: [ hasNameParam ] /classes/by-name: get: is: [ hasNameParam ] |
Import this API specs into Postman, you will see the following results: