viernes, 27 de mayo de 2016

RAML: THE RESTFUL API MODELING LANGUAGE (PART 9)

Traits:

You’ll probably have certain behaviors, policies or characteristics which are common across different endpoints. A good example is pagination; various collections which support pagination will no doubt use the same approach, to keep the API consistent. Or, as we’ve seen in the Security section, you may have different degrees of security, such as public or “authorization required”.
Rather than repeat the same configuration across multiple endpoints, you can define traits. By-and-large, the concept is synonymous with traits in PHP.
Here’s a simple example of creating a trait to indicate that the results from a given endpoint support simple pagination:
traits:
  - paged:
      queryParameters:
  page:
   description: Specify the page that you want to retrieve
   type: integer
   required: true
   example: 1
Now you can apply this to an endpoint using the is property, like so:
/albums:  
  get:
    is: [ paged ]
You can also pass in variables. As an example, let’s extend our paged trait to include a number of results per page. We’ll specify a maximum number of results per page, which can be overridden on a per-endpoint basis. Here’s the trait definition:
traits:
  - paged:
      queryParameters:
  page:
   description: Specify the page that you want to retrieve
   type: integer
   required: true
   example: 1
        perPage:
   type: integer
   description: The number of results per page, not to exceed <<maxPerPage>>
   maximum: <<maxPerPage>>
Notice how we can use the variable <<maxPerPage>> both as a maximum restriction, as well as substituting it into our generated documentation.
To use this, change the definition of the GET /albums endpoint to the following:
/albums:  
  get:
    is: [ paged : { maxPerPage : 50 } ]
You’ll find more examples of traits, along with resource types – which share certain characteristics with traits – in the specification. You’ll also find plenty of other documentation along with examples of some of the more complex scenarios you may need to describe.

No hay comentarios:

Publicar un comentario