Pengenalan RAML - Bahasa Pemodelan API RESTful

Artikel ini adalah sebahagian daripada siri: • Pengenalan kepada RAML - Bahasa Pemodelan API TERBAIK (artikel semasa) • Menghilangkan Redundansi RAML dengan Jenis dan Jenis Sumber

• Menggunakan RAML Modular Termasuk, Perpustakaan, Hamparan dan Sambungan

• Tentukan Properti RAML Tersuai Menggunakan Anotasi

1. Gambaran keseluruhan

Dalam artikel ini, kami memperkenalkan Bahasa Pemodelan API RESTful (RAML), bahasa spesifikasi terbuka, netral vendor yang dibangun di atas YAML 1.2 dan JSON untuk menerangkan API RESTful.

Kami akan merangkumi sintaks dan struktur fail RAML 1.0 asas semasa kami menunjukkan cara menentukan API berasaskan JSON yang mudah. Kami juga akan menunjukkan cara mempermudah penyelenggaraan fail RAML melalui penggunaan termasuk . Dan jika anda mempunyai API lama yang menggunakan skema JSON, kami akan menunjukkan cara memasukkan skema ke dalam RAML.

Kemudian kami akan memperkenalkan segelintir alat yang dapat meningkatkan perjalanan anda ke RAML, termasuk alat pengarang, penjana dokumentasi, dan lain-lain.

Akhirnya, kami akan menyelesaikan dengan menerangkan keadaan spesifikasi RAML terkini.

2. Menentukan API Anda (Membuat fail .raml )

API yang akan kami tetapkan agak mudah: memandangkan jenis entiti Foo , tentukan operasi CRUD asas dan beberapa operasi pertanyaan. Berikut adalah sumber yang akan kami tentukan untuk API kami:

  • DAPATKAN / api / v1 / musuh
  • POST / api / v1 / lawan
  • DAPATKAN / api / v1 / foos / {id}
  • PUT / api / v1 / musuh / {id}
  • HAPUS / api / v1 / foos / {id}
  • DAPATKAN / api / v1 / foos / name / {name}
  • DAPATKAN / api / v1 / foos? Name = {name} & ownerName = {ownerName}

Dan mari kita tentukan API kita menjadi tanpa status, menggunakan pengesahan HTTP Basic, dan akan dihantar disulitkan melalui HTTPS. Akhirnya, mari pilih JSON untuk format pengangkutan data kami (XML juga disokong).

2.1. Tetapan Tahap Root

Kita akan mulakan dengan membuat fail teks ringkas bernama api.raml ( awalan .raml disyorkan; namanya sewenang-wenang) dan menambahkan tajuk versi RAML pada baris pertama. Pada peringkat root fail, kami menentukan tetapan yang berlaku untuk keseluruhan API:

#%RAML 1.0 title: Baeldung Foo REST Services API using Data Types version: v1 protocols: [ HTTPS ] baseUri: //myapi.mysite.com/api/{version} mediaType: application/json 

Perhatikan pada baris 3 penggunaan pendakap {} di sekitar kata " versi ". Ini adalah bagaimana kami memberitahu RAML bahawa " versi" merujuk kepada harta tanah dan akan diperluas. Oleh itu baseUri yang sebenarnya adalah: //myapi.mysite.com/v1

[Catatan: sifat versi adalah pilihan dan tidak perlu menjadi bahagian dari baseUri .]

2.2. Keselamatan

Keselamatan juga ditakrifkan pada tahap akar fail .raml . Oleh itu, mari tambah definisi skema keselamatan asas HTTP kami:

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.

2.3. Jenis Data

Seterusnya, kami akan menentukan jenis data yang akan digunakan oleh API kami:

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

Contoh di atas menggunakan sintaks yang diperluas untuk menentukan jenis data kami. RAML menyediakan beberapa jalan pintas sintaksis untuk menjadikan definisi jenis kami kurang verbose. Berikut adalah bahagian jenis data yang setara menggunakan pintasan berikut:

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

The '?' watak berikut nama harta tanah menyatakan bahawa harta itu tidak diperlukan.

2.4. Sumber

Sekarang, kami akan menentukan sumber tahap tertinggi (URI) API kami:

/foos:

2.5. Parameter URI

Seterusnya, kami akan memperluas senarai sumber, membina dari sumber peringkat tertinggi kami:

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

Di sini, pendakap {} di sekitar nama harta menentukan parameter URI. Mereka mewakili tempat letak di setiap URI dan tidak merujuk sifat fail RAML peringkat akar seperti yang kita lihat di atas dalam deklarasi baseUri . Garis tambah mewakili sumber / foos / {id} dan / foos / name / {name} .

2.6. Kaedah

Langkah seterusnya adalah menentukan kaedah HTTP yang berlaku untuk setiap sumber:

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

2.7. Parameter Pertanyaan

Sekarang kita akan menentukan cara untuk bertanya koleksi foos menggunakan parameter pertanyaan. Perhatikan bahawa parameter pertanyaan ditentukan menggunakan sintaks yang sama dengan yang kami gunakan di atas untuk jenis data:

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

2.8. Tanggapan

Now that we've defined all of the resources for our API, including URI parameters, HTTP methods, and query parameters, it is time to define the expected responses and status codes. Response formats are typically defined regarding data types and examples.

JSON schema can be used instead of data types for backward compatibility with an earlier version of RAML. We'll 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.]

Let's start with the simple GET operation on /foos/{id}:

/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'd define the GET request on the /foos resource:

/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 define a response body containing an array of Foo objects, with the example being an array of JSON objects.

2.9. Request Body

Next, we'll define the request bodies that correspond to each POST and PUT request. Let's begin with creating a new Foo object:

/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

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 define the kind of response and a status code to expect when an error occurs.

Let's see how we would define the expected response for the GET request on the /foos/{id} resource when no resource is found with the given id:

 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 defined 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 defined 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 define the Foo object type at the root level of the .raml file using JSON schema:

types: foo: | { "$schema": "//json-schema.org/schema", "type": "object", "description": "Foo details", "properties": { "id": { "type": integer }, "name": { "type": "string" }, "ownerName": { "type": "string" } }, "required": [ "id", "name" ] }

And here is how you would reference the schema in the GET /foos/{id} resource definition:

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

4. Refactoring With Includes

As we can see from the above sections, our API is getting rather verbose and repetitive.

The RAML specification provides an include mechanism that allows us to externalize repeated and lengthy sections of code.

We can refactor our API definition using includes, making it more concise and less likely to contain the types of errors that result from the “copy/paste/fix everywhere” methodology.

For example, we can put the data type for a Foo object in the file types/Foo.raml and the type for an Error object in types/Error.raml. Then our types section would look like this:

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

And if we use JSON schema instead, our types section might look like this:

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 files, we can refactor our API using the include facility:

#%RAML 1.0 title: Baeldung Foo REST Services API version: v1 protocols: [ HTTPS ] baseUri: //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: 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 us with testing against a RAML API specification.

There is even a tool that will convert a Swagger JSON API into RAML.

Here is a sampling of available tools:

  • API Designer – a web-based tool geared towards rapid and efficient API design
  • API Workbench – an IDE for designing, building, testing, and documenting RESTful APIs that supports both RAML 0.8 and 1.0
  • RAML Cop – a tool for validating RAML files
  • RAML for JAX-RS – 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 – a syntax highlighter plugin for the Sublime text editor
  • RAML to HTML – a tool for generating HTML documentation from RAML
  • raml2pdf – a tool for generating PDF documentation from RAML
  • RAML2Wiki – a tool for generating Wiki documentation (using Confluence/JIRA markup)
  • SoapUI RAML Plugin – a RAML plugin for the popular SoapUI functional API testing suite
  • Vigia – an integration test suite capable of generating test cases based on a RAML definition

For a complete listing of RAML tools and related projects, visit the RAML Projects page.

7. The Current State of RAML

The RAML 1.0 (RC) specification gained release-candidate status on November 3, 2015, and at the time of this writing, version 1.0 was expected to be finalized within the 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 we may find useful along our journey with RAML.

  • RAML.org – the official site of the RAML specification
  • json-schema.org – the home of JSON schema
  • Understanding JSON Schema
  • JSON Schema Generator
  • Wikipedia RAML Page

9. Conclusion

This article introduced the RESTful API Modeling Language (RAML). We demonstrated some basic syntax for writing a simple API specification using the RAML 1.0 (RC) spec.

And we saw ways to make our definitions more concise by using syntactical shortcuts and externalizing examples, data types, and schemas into ‘include' files.

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.

Dengan pelepasan rasmi versi 1.0 yang akan datang, ditambah dengan sokongan hebat dari pembangun alat, nampaknya RAML ada di sini untuk tetap tinggal.

Seterusnya » Hilangkan Redundancy di RAML dengan Jenis dan Ciri Sumber