Designing APIs in RAML with Mulesoft’s Anypoint Platform

Who is Mulesoft?

Mulesoft is a software company that provides an enterprise technology called Anypoint Platform. It can be used to implement, maintain and govern an increasing number of applications and systems.

In short, they aim to unify data to deliver and build connected APIs through API-led approach.

It was acquired by Salesforce for around $6.5 billion in a deal completed in March 2018.

More information on their website.

Overview

Thousands of enterprises use Anypoint Platform because it has an emphasis on consumption (feedback and usage metrics) as much as production (reusable assets).

Originally built as a single solution, the platform allows developers to design, develop, manage, integrate and deploy APIs.

Segments of it include :

  • Design center : Used for rapid development (designing, documenting and mocking)
  • Exchange : Used to collaborate, discover assets and get stakeholder feedback
  • Management center : Used to manage different aspects of the application

To support all of this, Mulesoft uses Mule Runtime as a dedicated server to deploy applications. These applications can be MuleSoft-hosted through CloudHub or customer-hosted in the cloud.

Applications can be created virtually through Flow Designer and Anypoint Studio or by writing XML based code.

Under the hood, all Mule applications are written in Java using the Spring framework.

If you’re interested in how to create web services using Spring, you can click here for one of our most popular articles on the subject.

The modern API, a core enabler of a new operating model is characterized by having :

  • Discoverable and accessible through a self-service
  • Productized and designed for ease of consumption
  • Easily managed for security, scalability and performance

This approach is called API-led connectivity.

Wrong way of doing API-led connectivity
Right way of doing API-led connectivity

To achieve an unified application network of data, devices and APIs, there are some guidelines :

  • Emerges bottoms-up via self-service
  • Provides visibility, security and governability at every API node
  • Network is built for change

What is an API?

API stands for Application Programming Interface and it basically provides the info on how to communicate with implemented software components, defining the :

  • Operations (what to call)
  • Inputs (what to send)
  • Outputs (what to get back)
  • Underlying data types

There are basically two main types of web services or APIs :

  • SOAP : Traditional, more complex, based in XML
  • REST : Recent, simpler, based in the HTTP communication protocol

REST stands for Representation State Transfer and is defined by an architectural style where clients and servers exchange representations of resources.

The HTTP request indicates which operation should be performed on the object identified by the URL. Some examples of such operations :

  • GET /users
  • GET /users?country=Brazil
  • GET /users/3
  • POST /users with JSON/XML in HTTP body
  • DELETE /users/3
  • PUT /users/3 with JSON/XML in HTTP body

A RESTful web service can return data in many possible ways. A popular way is through JSON (JavaScript Object Notation) which is a lightweight data-interchange format that is readable to humans and supports collections and maps.

Como carregar dados JSON do Cloud Storage | BigQuery | Google Cloud
JSON data example

To design an API successfully, developers need to focus on performance of client applications such as Postman and ARC without forgetting about user experience.

Below is the API development cycle, specified by the Anypoint Platform as a good practice model :

Development cycle

Getting started with the Anypoint Platform

In the Design Center, a new application can be created by going through “Create new” -> “Create new application”.

First step when creating an application

After setting the name of the application (we’ve set ours to “CodeFiction App”) and clicking “Create”, a flow is generated and you’ll be redirected into the Flow Designer.

We’re able to assert that our application is up and running by checking the Logs tab located in the lower-right corner of the window.

If you’re unfamiliar with requests and endpoints testing, you can click here for more information on the subject of using Postman as a web client to verify endpoints.

Defining an API with RAML

Defining the specifications of an API such as resources, request methods and paths is not as complicated as one would think when working with the Anypoint Platform.

As with any project in the beginning :

  1. Go to the Design Center
  2. Go through “Create new” -> “Create API specification”
  3. Set the project name and click “Create Specification”

After creating our project, we start by defining our resources and its supported request methods in RAML, a YAML and JSON human-readable serialization format.

#%RAML 1.0
title: CodeFiction API

/users:
  get:
    queryParameters:
      origin:
        required: false
        enum:
          - BR
          - US
          - ES
  post:
  
  /{ID}:
    get:

All resources are objects identified by the web service URL that you want to act upon using the HTTP method used for the request. They can be identified by a slash “/” before their name.

An important detail about editing RAML code is indentation, which indicates subordination and denotes the code which is a part of the function (or subordinate to the function call).

In the API console, by clicking the GET method we defined for the /users resource, information about the selected method shows up.

To test the path defined, we can click the “Try it” button. Of course, it won’t do anything now because we need to define a URL to call in the RAML definition.

Turn on the mocking service on top of the API console to activate a a mocking URL with the purpose of testing our defined method.

Mocking service button

A 200 OK status code and an empty response should show up, indicating that everything is working as expected.

We can test our nested ID resource and our POST method the same way, resulting in a generic 200 status code response.

Adding a data type to an API resource

For any request, it’s important to specify the data types, descriptions and examples for the data in question.

To add a data type to our users resource, we need to create a file and specify a model to its properties and attributes.

  1. Create a new file
  2. Select “Data type” as category and set the file name
Add new data type file

We can now set the properties of our resource inside the newly created file.

#%RAML 1.0 DataType

type: object
properties: 
  ID?: integer
  name: string
  lastname: string
  origin: string

Now to include these properties in the resource, we need to go back to our codefiction-api.raml file and update the code to specify our user type along with some http response configuration.

#%RAML 1.0
title: CodeFiction API

types:
  Users: !include /users-data-type.raml

/users:
  get:
    queryParameters:
      origin:
        required: false
        enum:
          - BR
          - US
          - ES
    responses:
      200:
        body:
          application/json:
            type: Users[]
  post:
  
  /{ID}:
    get:

Any methods and params nested under a resource belong to and act upon that resource.

Adding an example data response to an API resource

To add an example response to our users resource, we need to create a new file in the same way we did before and fill it with user data.

Add new example data file

We can set the attributes of our example data inside the newly created file.

#%RAML 1.0 NamedExample
value:

  - 
    ID: 1 
    name: John
    lastname: Doe
    origin: US
  - 
    ID: 2 
    name: Carlos
    lastname: Herrera
    origin: ES
  -
    ID: 3 
    name: João
    lastname: Silva
    origin: BR

To include this data in the resource, we need to go back to our codefiction-api.raml file and update the code to include our output under the responses keyword with the appropriate indentation.

#%RAML 1.0
title: CodeFiction API

types:
  Users: !include /users-data-type.raml

/users:
  get:
    queryParameters:
      origin:
        required: false
        enum:
          - BR
          - US
          - ES
    responses:
      200:
        body:
          application/json:
            type: Users[]
            examples:
              output: !include /users-example.raml
  post:
  
  /{ID}:
    get:

By sending a GET request to our users resource now with the mocking service turned on, we should get a 200 OK response with the example data displayed.

Example data displayed

We can do the same thing for our ID resource by creating an example file to handle single users requests.

#%RAML 1.0 NamedExample
value:
    ID: 1 
    name: John
    lastname: Doe
    origin: US

The example file needs to be also included into our main api file under the correct resource with some additional configuration, the same way we did with the users resource example data.

#%RAML 1.0
baseUri: https://anypoint.mulesoft.com/mocking/api/v1/links/3cd3d8d2-f5a1-4939-8b92-2809c9e02c49/ # 
title: CodeFiction API

types:
  Users: !include /users-data-type.raml

/users:
  get:
    queryParameters:
      origin:
        required: false
        enum:
          - BR
          - US
          - ES
    responses:
      200:
        body:
          application/json:
            type: Users[]
            examples:
              output: !include /users-example.raml
  post:
  
  /{ID}:
    get:
      responses:
        200:
          body:
            application/json:
              type: Users
              examples:
                !include /users-detail-example.raml

It’s important to note that all documentation is auto-generated from the RAML file and displayed in the API console.

Endnotes

You can find the supporting source code available for this API in our GitHub repository here.

Feel free to leave a comment below if there’s something more you’d like to see covered in future articles regarding the Anypoint Platform or API development.

See you next time !

About the author

Website | + Posts

Software Consultant with more than 11 years experience, most of that in Finance area. I love building things and see them running and making a difference.

Specialised in Golang (2 years), Java (11 years), Javascript, React and Angular (1 year), PHP (2 years), project management and delivery leading (2 years), mentoring and coaching (1 year).

Website | + Posts

Electrical engineering student from Brazil passionate about learning and teaching people.

Had some professional and academic engineering experiences, now my focus is on studying and developing software as a full time job.

Leave a Reply

Your email address will not be published. Required fields are marked *