Chapter 1. Prototyping

We want the integrations in this book to be created as part of an application network so other users in the enterprise can find, use, and share the applications. We also want the user story to be captured into an interactive API specification, which will ensure that the API is built for business requirements and is not just an afterthought to service the backend. This approach to asset creation will encourage reuse and drive integration success.

In recent years, spec-driven development has emerged as a significant trend in contemporary business systems. We’ve observed a correlation between spec-driven development and continued success in creating robust, scalable, and successful application networks. Previously, API development was implementation-driven, with developers quickly prototyping endpoints without initially considering an API specification. But as the code evolved, it caused a lot of problems due to outdated documentation and specifications. Keeping up with all the layers of software development became increasingly difficult. IT began to grow rapidly, and as a result, the product teams struggled to keep up with the disruptions, leading to a significant backlog.

Spec-driven development allows developers to design specifications. It is a process that enables developers to design a specification first, write code according to the design, and then maintain the specification. MuleSoft, with its tools like Anypoint Platform and Anypoint Exchange, takes this process to the next level. It allows developers to design the specification and use mocking service to test the API. This helps to improve the API specification and get business buy-in even as part of continuous API development. Anypoint Platform also makes it easier to manage and maintain APIs and apply security measures. With MuleSoft Anypoint Studio or Anypoint Code Builder(ACB), developers can use the approved specification to auto-create HTTP routing code, which accelerates the app development process.

This chapter introduces API design using Mulesoft at a basic practitioner level. It shows you how to use the Anypoint Platform and, in particular, how to use API Designer and Anypoint Exchange to create and publish API specifications. It also demonstrates different languages for writing API specifications, such as RAML and OpenAPI Specification (formerly Swagger), to write API specifications and compares the two.

Note

There are many API design tools available in the market, with the most popular being Swagger, Postman, API Dog, Paw, Apigee, Spotlight, and Apiary, among many others. Remember that the choice of tool depends on your specific needs, team preferences, and the complexity of your API project. We highly recommend you use API Designer, available on Mulesoft’s Anypoint Platform, because it helps with seamless integration and code building.

This is an important chapter, but it’s not a comprehensive guide to REST API’s. Instead, it gives you sufficient exposure to be able to work through the solutions contained in the rest of this book and develop robust Mulesoft APIs. For more in-depth information, there are many good books on the topic, such as REST in Practice by Jim Webber, Savas Parastatidis and Ian Robinson (O’Reilly).

API Fundamentals

Before we jump right in and start designing the APIs, let’s first look at API fundamentals. API stands for application programming interface. APIs are integration points, basically sets of rules and protocols that allow different software applications to communicate with each other. Let’s say you are at a restaurant and want to order shawarma. You don’t need to know how the kitchen operates or who the chef is. All you need is to ask for the menu and then tell the server what you want. In this case, you’re the client, the server is the API, the menu is the resource serviced, and the kitchen is the backend system. They handle your requests and deliver responses while taking care of all the complex processes behind the scenes.

An API consists of endpoints, specific URLs that represent resources or functionalities provided by the API, and methods that define the actions you can take on these endpoints, such as getting data or submitting requests. When you make a request, you can include parameters to provide context or criteria for the desired operation. The response you get back will include the outcome along with any requested data or metadata. Authentication and authorization mechanisms ensure that your access to resources is secure while documentation explains the API’s endpoints, methods, authentication methods, and usage examples.

The set of rules, conventions, and standards that govern how different software applications communicate and interact with each other over a network are together called a protocol. API protocols are important because they help in consistent communication. They guide how requests should be formatted and structured, what methods or operations are supported, and how errors are handled.

There are several API protocols that developers use, such as REST (Representational State Transfer), SOAP (Simple Object Access Protocol), WebSocket, GraphQL, and gRPC (Google Remote Procedure Call). Each protocol has its unique characteristics, benefits, and ideal use cases, allowing developers to create software for various needs and requirements. However, SOAP and REST are the two main web service protocols. Complying with the established protocols’ rules and guidelines helps developers ensure that their applications can communicate with other applications on the network.

SOAP Web Services

SOAP web services use XML(eXtensible Markup Language) to exchange information over the internet. When you send a message using SOAP, it’s like putting it in a special envelope. This envelope has different sections, like the address (where the message is going), any extra notes (like a header), and the main message itself (the body). These sections help keep everything organized and make sure the message gets to where it needs to go.

Now, the cool thing about SOAP is that it works with standard internet protocols like HTTP or SMTP, which means it can be used with all sorts of different systems and technologies, making it platform and operating service independent. Plus, it’s secure because it can encrypt messages, make sure they’re from the right person (authentication), and keep them safe from tampering (message integrity). You can secure SOAP messages without using policy sets for configuration by using the Web Services Security APIs (WSS API). To configure the client for request encryption on the generator side, use the WSSEncryption API to encrypt the SOAP message. The WSSEncryption API specifies which request SOAP message parts to encrypt when configuring the client.

SOAP also lets you send complex data and organize it neatly, which is handy for big companies with lots of different systems that need to talk to each other. So, whether you’re building a big enterprise system or just want your apps to play nice together, SOAP is there to make sure everything runs smoothly.

Let’s say we want to retrieve geolocation information for Sherlock Holmes’s address. We’d make a SOAP request like in Example 2-1.

Example 2-1: SOAP call to GET address

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:web="http://www.example.com/webservices">
    <soapenv:Header/>
    <soapenv:Body>
        <web:GetGeolocation>
            <web:Address>221B Baker Street</web:Address>
        </web:GetGeolocation>
    </soapenv:Body>
</soapenv:Envelope>

REST Web Services

REST is an architectural style, where the client and server exchange representations of resources. When you use RESTful web services, you interact with resources (like data or functionalities) using standard actions, such as GET (to fetch data), POST (to create new data), PUT (to update existing data), and DELETE (to remove data). One important thing about REST is that it keeps things simple by not remembering the client state from previous requests (meaning it is stateless). This makes it faster and more efficient. Also, clients can cache previous responses, so they don’t have to ask for the same information over and over again.

In REST, everything is a resource. Resources can be objects, data, or services. REST also relies on URLs (uniform resource locators) to identify resources, just like addresses tell you where a place is. For example, to get geocode for an address, call "https://maps.com/geocode“.

Accessing or modifying resources is done through a specific set of operations, and RESTful web services respond with an HTTP status code that indicates the outcome of the operation (success, failure, update). This section is a brief explanation of how it works.

GET

Imagine you’re using a mapping app and you want to find the location of a specific restaurant, say Torchy’s Tacos. You open the app and type Torchy’s Tacos in the search bar. The app then retrieves the current location of Torchy’s Tacos and displays it on the map. In this scenario, your search request to the mapping app is like a GET request, and the app’s response, showing the location of Torchy’s Tacos, is like the server’s response, providing you with the current state of the resource (the restaurant’s location) in a representation (the map).

In Example 2-2, the HTTP method GET is used to indicate that the request is for retrieving data from the server. The URL path /locations/joes_pizza specifies the resource that needs to be retrieved, which in this case is the location information for Torchy’s Tacos.

Example 2-2: GET request to get the location for Torchy’s Tacos.

GET /locations/joes_pizza

When the server receives this request, it responds with the details of Torchy’s Tacos, as shown in Example 2-3, typically in JSON format.

Example 2-3: Success response for the GET request.

HTTP/1.1 200 OK
Content-Type: application/json
{
  "name": "Torchy's Tacos",
  "address": "123 Main Street",
  "category": "Restaurant",
  "latitude": 40.7306,
  "longitude": -73.9352
}

In Example 2-3, 200 OK indicates that the request was successful, and the server is returning the requested data. Content-Type: application/json specifies that the response body is in JSON format. The Body contains the details of Torchy’s Tacos, including its name, address, category, latitude, and longitude.

POST

Now let’s say you discover a new café that’s not on the map yet, and you want to add it. You open the app, go to the Add Location section, and fill out a form with all the details about the café - its name, address, opening hours, and so on. You then submit the form, and the app adds the café to its database and displays it on the map. A post body is shown in Example 2-4. In this scenario, filling out the form and submitting it to the mapping app is like sending a POST request to the server, asking it to create a new resource (the café) based on the information provided.

Example 2-4: POST body to add a location.

{
  "name": "Orielly Cafe",
  "address": "331 Coffee Street",
  "category": "Café",
  "latitude": 40.7128,
  "longitude": -74.0060
}

When you send a POST request to create a new location, the server responds with a confirmation message or the newly created resource. Example 2-4 shows an HTTP response for the POST call.

Example 2-4: POST response.

HTTP/1.1 201 Created
Content-Type: application/json
 
{
  "message": "Location created successfully",
  "location_id": "123"
}
DELETE

Continuing with the mapping app analogy, let’s say you find an old location on the map that’s no longer there, like a closed-down bookstore. You tap on the location and select Delete. The app then removes the bookstore from its database and updates the map accordingly, removing the location from view. This act of deleting the outdated location from the map is like sending a DELETE request as shown in Example 2-5 to the server, asking it to delete the resource (the bookstore’s location) from its records.

Example 2-5: DELETE request to delete the bookstore’s location

DELETE /locations/cafe_Orielly
PUT

Imagine you come across a location on the map with the wrong name listed - instead of “Torchy’s Tacos,” it says “Joe’s Pizzeria.” You tap on the location, select Edit, and correct the name to “Torchy’s Tacos”. The app then updates its database with the corrected information and displays the updated name on the map. This process of providing corrected information and updating the map is like sending a PUT request to the server. A PUT body is shown in Example 2-6, asking it to replace the entire resource (the location’s information) with the new information provided. Example 2-6 an example of the JSON payload you might send.

Example 2-6: PUT body to correct a resource.

{
  "name": "Torchy's Tacos",
  "address": "331 Taco Street",
  "category": "Restaurant",
  "latitude": 40.7306,
  "longitude": -73.9352
}

When the server receives this request, it updates the existing resource (location) for Torchy’s Tacos with the new address and gives the response shown in Example 2-7.

Example 2-7: PUT response.

HTTP/1.1 200 OK
Content-Type: application/json
 
{
  "message": "Location replaced successfully"
}
PATCH

Finally, let’s say you discover a small error in the address of a location - instead of “123 Main Street”, it should be “123 Main Avenue”. You tap on the location, select Edit, and correct the address. The app then updates its database with the corrected address without changing anything else. This act of making a small correction to the existing information is like sending a PATCH request to the server, asking it to make a partial update to the resource (the location’s address).

When you send a PATCH request to update part of a location’s information, the server responds with a confirmation message or the updated resource. Example 2-8 shows the HTTP response for a PATCH call.

Example 2-8: PUT response

HTTP/1.1 200 OK
Content-Type: application/json
 
{
  "message": "Location updated successfully",
  "updated_fields": ["address"]
}
 

A good API should return status codes that align with the HTTP specifications. Table 2-1 has a list of common HTTP codes.

Table 1-1. List of HTTP codes
Code Definition Returned By
200 OK – The request succeeded GET, DELETE, PATCH, PUT
201 Created – A new resource or object in a collection POST
400 Bad Request – The request could not be performed by the server due to bad syntax or other reason in the request
ALL
401 Unauthorized – Authorization credentials are required or the user does not have access to the resource/method they are
requesting
ALL
404 Resource not found – The URI is not recognized by the server ALL
500 Server error – Generic something went wrong on the server side
ALL

REST is more flexible than SOAP when it comes to data formats because SOAP is limited to XML. REST follows widely accepted standards such as HTTP and JSON, which makes it easier to use compared to SOAP, and it has its own standards like WSDL and WS-Security which can be complicated. Both protocols support security, but SOAP has built-in standards for authentication, encryption, and digital signatures. REST relies on external security mechanisms like OAuth or API keys for security. This makes REST protocol more popular for the development of web services.

Efficient, scalable, and maintainable RESTful APIs can be achieved by following best practices. Here are some REST best practices we will use in this book:

  • Resource-oriented URIs: Using nouns instead of verbs in URIs to represent resources. For example, use /users instead of /getUsers. Our goal is to transfer representations back and forth and not methods or states.

  • Correct HTTP method usage: Use HTTP methods (GET, POST, PUT, DELETE, PATCH) according to their intended purpose: GET for retrieval, POST for creation, PUT for replacement, DELETE for removal, and PATCH for partial updates. It is important to follow this to maintain consistency in the API spec.

  • Plural nouns for collections: Use plural nouns when representing collections of resources. For example, instead of using /user, it is better to use /users. This ensures consistency and clarity in your API design.

  • Consistent resource naming: Maintain consistent naming conventions for all your resources. Doing so can not only increase understanding but also make it easier for developers to use your API to its full potential.

  • Proper HTTP status codes: Use the appropriate HTTP status codes to represent the outcome of requests. For instance, use 200 to indicate success, 201 for successful creation, 404 for resource not found, and 400 for bad requests.

  • Versioning: Include a version number in URIs or headers to ensure backward compatibility when making changes to the API.

  • Query parameters for Filtering, Sorting, and Pagination: Use query parameters to enable clients to filter, sort, and paginate large collections of resources effectively.

  • Consistent response structure: Maintain consistency in the structure of API responses, including data format (e.g., JSON) and the layout of success and error responses. Where possible, we will achieve this by using fragments to promote consistency and asset reuse.

  • Graceful error handling: Provide clear and concise error messages along with appropriate HTTP status codes to assist in troubleshooting. These error messages should offer meaningful information about what went wrong and how to resolve the problem. For instance, if a client requests a resource that does not exist, the error message should read something like “User with ID 123 not found”.

  • Security measures: Add authentication and authorization to secure the API from unauthorized access and attacks by creating and using security schemas.

  • Documentation: Document the APIs so users know what resource endpoints, request/response formats, authentication methods, and usage examples to assist developers in effectively utilizing the API.

To design and document REST APIs, you can utilize API specification languages. A variety of popular languages are available, such as OpenAPI (formerly Swagger), RAML (RESTful API Modeling Language), API Blueprint, and GraphQL SDL (Schema Definition Language). The next sections will explore OpenAPI and REST. However, for the remainder of this book, REST will be our preferred language for design and development.

RAML

RAML is a language to describe RESTful APIs. It has a concise syntax, supports data types, security definitions, and resource hierarchies, and allows easy generation of API documentation. Example 2-9 shows a simple RAML file for /GET users endpoint.

Example 2-9 /GET users endpoint

#%RAML 1.0
title: My API
version: v1
/users:
  get:
    description: Get a list of users
    responses:
      200:
        body:
          application/json:
            example: |
              [{"id": 1, "name": "Alice"}]
 

API documentation can be generated easily from RAML files with the use of tools such as api-console or RAML2HTML. RAML files can be used by API gateways like MuleSoft Anypoint Platform or Apigee to configure routing, security, and transformations. All of these features make RAML a better fit for creating APIs to build application networks when compared to other API modeling languages. RAML syntax is based on YAML and JSON, which makes it lightweight and human-readable. The syntax uses indentation to specify data hierarchy. Figure 1-3 shows a sample RAML file written using YAML; note the data hierarchy specified by indentation.

Sample RAML file showing lines to indicate indentation
Figure 1-1. Sample RAML file showing lines to indicate indentation

Although not all components are necessary for every API, it is important to understand how an API is designed and constructed. The following components cover particular aspects of RAML API design:

  • Basic structure: RAML documents start with the RAML tag followed by the version number and other metadata as shown in Example 2-10.

Example 2-10: RAML documents start with RAML tag

#%RAML 1.0
title: Example API
version: v1
 
  • Resource definition: Using the resource keyword followed by the path and a nested block, methods and parameters are defined for resources. In Example 2-11, a nested block is shown for the resource /users.

Example 2-11: Resources are defined using resource keywords.

 
/users:
  get:
    description: Retrieve all users
    responses:
      200:
        body:
          application/json:
            example: |
              [
                {"id": 1, "name": "Olive"},
                {"id": 2, "name": "Summer"}
              ]
 
  • Methods: Resource blocks define methods (GET, POST, PUT, DELETE) and their properties, like description, query parameters, and request/response bodies.

  • Parameters: Parameters can be defined at the API or resource level using the parameters keyword. They can include query parameters, URI parameters, headers, and so forth. Example 2-12 shows /users/{userId} resource path includes a URI parameter {userId}. URI parameters are enclosed in { }.

Example 2-12: RAML with URI parameters.

#%RAML 1.0
title: Users API
version: v1
 
/users/{userId}:
  uriParameters:
    userId:
      description: The ID of the user
      type: integer
      required: true
  get:
    description: Retrieve a user by ID
    responses:
      200:
        body:
          application/json:
            example: |
              {
                "id": 123,
                "name": "Olive A",
                "email": "olive@example.com"
              }
      404:
        description: User not found
  put:
    description: Update a user by ID
    body:
      application/json:
        example: |
          {
            "name": "Summer Autum",
            "email": "summer@example.com"
          }
    responses:
      200:
        description: User updated successfully
      404:
        description: User not found
  • Responses: Method blocks use the responses keyword to define responses, each with a status code, headers, and body.

  • Data types: In RAML, the types keyword allows for the definition of custom data types that can be used throughout an API. By defining these types, you can ensure consistency in data structures and avoid repetition of code. Custom data types can be used to represent anything from basic types, such as numbers or strings, to more complex structures like arrays or objects. Additionally, these data types can be reused throughout an API, making it easier to maintain and scale the API over time..

  • Includes and libraries: RAML enables extracting part of large API definitions into smaller, reusable components by utilizing includes and libraries. This makes it easy to reuse part of the API code. For example, error objects can be extracted into separate fragments and then reused throughout the organization.

  • Security schemes: API-level security schemes can specify authentication methods such as OAuth or API keys. This helps make APIs more secure.

  • Annotations: Annotations can be added to different elements of the RAML file to provide additional metadata and documentation.

Remember the Google Maps system API we discussed in our use case? Now, let’s apply all our learning to write Google Maps system API specifications for interacting and integrating with Google Maps. We will use the design center on Anypoint Platform to create the API specification.

Note

The system API called google-maps-sapi is an API that will represent the system layer in our integration.

To start, click Design Center and click the Create button. Figure 2-2 shows the Create button in the Design Center.

  2  Create button for creating API specification
Figure 1-2. - 2: Create button for creating API specification

Anytime you want to create a new API specification, you click Create and choose New API Specification, from the drop-down, as shown in Figure 1-3, and begin.

Drop down options for Design Center asset creation.
Figure 1-3. Drop-down options for Design Center asset creation.

Next, you will see a pop-up and you can choose to design the specification either using the text editor or visual editor. In Figure 1-4, you see two options. If you choose the first one, “I am comfortable designing it on my own,” he text editor opens; if you choose “Guide me through it” the visual editor for specification design will open. Let’s first design using the text editor.

Choose the specification design options
Figure 1-4. Choose the specification design options

Design Center: Text Editor

When you select option two in Figure 1-4, it opens the text editor. Figure 2-5 shows the Design Center text editor option. It has a file browser, editor, API console, and shelf.

 5  Design Center text editor with a sample API specification.
Figure 1-5. -5: Design Center text editor with a sample API specification.

Begin by adding the basic tags and title and then you start adding the resource. Example 2 -13 shows a resource added.

Example 2- 13 RAML with resource /geocode added, the color coding is based on how it appears in the text editor.

#%RAML 1.0
title: Google Maps SAPI Integration
 
/geocode:
  

Next you define the methods. In our case, we are using the GET method to retrieve the geocode, shown in Example 2-14. It’s best practice to write the description, and if you want to use your API spec as a connector you’ll need to specify the displayName.

Example 2-14: GET method with display name

#%RAML 1.0
title: Google Maps SAPI Integration
 
/geocode:
  get:
    description: Retrieve geolocation information based on an address
    displayName: get geocode
 

Start by adding any necessary query parameters for the method you’re working on. Note the indentations in the specifications, as shown in Example 2-15.

Example 2-15: Query parameters for HTTP method

/geocode:
  get:
    description: Retrieve geolocation information based on an address
    displayName: get geocode
    queryParameters:
      address: string
 

Now you can interact with the API using API Console. Example 2-15 shows a RAML for google-maps-sapi with methods, responses, and examples. When we talk about responses, we’re laying out a map. This map shows what could happen with different HTTP status codes. For each status code, we’ll explain what kind of data might come back, describe it a bit, and throw in some examples to make it clear.

Example 2-15: RAML for google-maps-sapi

#%RAML 1.0
title: Google Maps SAPI Integration
version: v1
baseUri: https://maps.google.sapi.com/maps/api
mediaType: application/json
 
/geocode:
  get:
    description: Retrieve geolocation information based on an address
    displayName: get geocode
    queryParameters:
      address: string
    responses:
      200:
        body:
          application/json:
            example: |
              {
                "latitude": 34.0522,
                "longitude": -118.2437
              }
 
/directions:
  get:
    description: Get directions between two locations
    displayName: get directions
    queryParameters:
      origin: string
      destination: string
    responses:
      200:
        body:
          application/json:
            example: |
              {
                "route": "Take I-405 S",
                "duration": "30 mins"
              }
 
/places:
  get:
    description: Search for places near a specific location
    displayName: get nearby locale
    queryParameters:
      location: string
      type: string
    responses:
      200:
        body:
          application/json:
            example: |
              {
                "results": [
                  {
                    "name": "Central Park",
                    "type": "Park"
                  }
                ]
              }

When it comes to showing examples of data, there are two options: example and examples. If we use example, it’s for showing just one example of what the data might look like. But if we go with examples, that’s for when we want to show multiple examples. We’ll organize these examples like a map, with key-value pairs as shown in Example 2-16.

Example 2-16: Examples in RAML

responses:
      200:
        body:
          application/json:
            examples:
              example1: |
                {
                  "status": "success",
                  "results": [
                    {
                      "address": "221B Baker Street, London, UK",
                      "latitude": 51.523767,
                      "longitude": -0.158371
                    }
                  ]
                }
              example2: |
                {
                  "status": "success",
                  "results": [
                    {
                      "address": "12 Grimmauld Place, London, UK",
                      "latitude": 51.530297,
                      "longitude": -0.123735
                    }
                  ]
                }

Design Center: Visual Editor

To create API specifications in RAML 1.0 or OAS 2.0/3.0 (JSON) using the visual API editor in API Designer, you simply fill out straightforward forms that aren’t tied to any specific programming language. To get to the visual editor: Select the option “Guide me through it” to utilize the visual API editor and click Create API Spec to complete the process.

Figure 1-5 -6 shows how the visual editor is organized. In the left panel, you’ll find your API spec’s name displayed along with buttons for creating resources, data types, and security schemes. Everything you generate here becomes part of the specification and remains within the same file. The middle panel is where you input details about your API components. Upon opening the editor, you’ll encounter a form for the primary properties of your spec. Click items in the left panel to view their respective forms here. The right panel provides read-only views: the RAML viewer and the OAS viewer. You can toggle between them using tabs. They present your spec in either RAML 1.0 or OAS 3.0 format. As you fill out forms in the middle panel, the draft updates accordingly here. Additionally, you can initiate a mocking service from the panel to test the endpoints you’ve configured in your spec.

Visual Editor
Figure 1-6. Visual Editor

OAS: Open API Specification

Now that you have have been introduced to RAML, let’s look into the second specification language used in Anypoint Design Center, known as Open API Specification (OAS). Example 2-17 shows a simple OAS file for /GET users endpoint.

Example 2-17 /GET users endpoint

{
  "openapi": "3.0.0",
  "info": {
    "title": "My API",
    "version": "v1"
  },
  "servers": [],
  "paths": {
    "/users": {
      "get": {
        "responses": {
          "200": {
            "description": " ",
            "content": {
              "application/json": {
                "schema": {
                  "example": [
                    {
                      "id": 1,
                      "name": "Alice"
                    }
                  ]
                }
              }
            }
          }
        },
        "description": "Get a list of users",
        "operationId": "GET_users"
      }
    }
  },
  "components": {
    "schemas": {},
    "responses": {},
    "parameters": {},
    "examples": {},
    "requestBodies": {},
    "headers": {},
    "securitySchemes": {},
    "links": {},
    "callbacks": {}
  }
}
 

Both RAML and OAS are API specification languages that allow developers to define their APIs. However, they differ in some aspects. RAML comes with its data modeling language called Data Types, which makes it easy to define reusable data structures. On the other hand, OAS relies on JSON Schema for data modeling, which offers more advanced validation capabilities.

RAML allows for the creation of resource types, traits, and libraries within the API specification, providing flexibility and organization. OAS introduced components like schemas, parameters, and responses in version 3.0 to promote reuse, but it’s not as flexible as RAML.

RAML has a smaller ecosystem than OAS, but it’s supported by tools like API consoles, mocking services, and code generators. In contrast, OAS has a larger ecosystem with extensive support, including editors, validators, documentation generators, and code generators.

Note

Ultimately, it’s your decision whether to use RAML or OAS, and the decision will depend on factors such as business decisions, persona/project preference, existing infrastructure, and community support.

Anypoint Code Builder

It is possible to create API specifications using Anypoint Code Builder. To create an API spec project in Anypoint Code Builder, click  (Anypoint Code Builder) and choose Design an API from the quick actions menu, as shown in Figure 1-7.

Anypoint Code Builder menu items
Figure 1-7. Anypoint Code Builder menu items.

Fill in the API specification form in the dialog box shown in Figure 1-8. The Project Name is the unique name for your project, for example, google-maps-sapi. Project location must be a local directory or another directory you want to store the project in—it is not a best practice to create a project directory inside another project directory. API specification language can be RAML or OAS 3.0.

Form to create an API specification.
Figure 1-8. Form to create an API specification.

To get started, click the Create Project button. If you are prompted to trust the authors of the files in the folder, go ahead and do so. Once the project is ready for editing, the API project will open the specification in the Editor view (Figure 1-9). This may include an OAS 3.0 (YAML) spec, for example.

Form to create a fragment.
Figure 1-9. Form to create a fragment.

When designing your API fragment, remember to use auto-complete (Ctrl + Space) to view available options within the context. If you have created an OAS 3.0 (YAML) fragment project, you can test adding fragments to a spec by replacing the initial API fragment with the example code (Figure 1-10).

A fragment being edited.
Figure 1-10. A fragment being edited.

Next, to publish the asset, select View > Command Palette(Ctrl+Shift+P), as shown in Figure 1-11.

Select View and then Command Palette to execute commands.
Figure 1-11. Select View and then Command Palette to execute commands.

Type the following command, as shown in Figure 1-12, to publish the specification:

Mulesoft: Publish API Specification to Exchange
Note

To select and import an asset from Exchange, use the command: Mulesoft: Add Fragment dependency from Exchange and then verify that the fragment dependency was added by checking the dependencies section of the exchange.json file.

The command to publish Assets using Anypoint Code Builder.
Figure 1-12. The command to publish Assets using Anypoint Code Builder.

If prompted, click the Allow button and follow the prompts to sign in to Anypoint Platform. In the Select a Business Group section, search and choose your business group for the project. Next, in the Set Project Name section, confirm or type the project name and press Enter. After that, confirm or make changes to each item (Artifact ID, Asset version, and API version) and press Enter. If you wish to cancel publishing, press the escape (Esc) button. The status bar will display the progress. Once it is complete, you will receive a message saying that the API specification has been successfully published to Exchange.

Note

If your API specification appears on Exchange as a REST API rather than an API spec fragment, ensure that the classifier attribute in the exchange.json file in your project folder in your IDE is set to one of the following values, depending on the language used:

  • For OpenAPI Specification (OAS), set the classifier attribute to oas-components.

  • For RAML, set the classifier attribute to raml-fragment.

  • For JSON Schema, set the classifier attribute to json-schema.

If the classifier attribute is set to one of the following values, the project is considered an API specification rather than a fragment:

  • For OAS, the classifier attribute should be set to oas.

  • For RAML, the classifier attribute should be set to raml.

Summary

After completing this chapter, you should now know how to create API specifications. Our main goal was to learn how to design APIs with consistency and clarity. However, our ultimate goal is to use these API specifications to create an application network that promotes the reuse of assets. It’s important to note that you can use your own Source Control Management (SCM) system when designing API’s in ACB. This allows for greater flexibility and control over your API specifications.

In the next chapter, we will create API fragments that will allow us to reuse APIs and parts of the API, known as API fragments, and apply them to the use case and existing specifications. We will also explore how to apply security schemes to API specifications, publish APIs, and enable mocking. This will enable us to share the APIs we have created with others to try out and provide us with feedback.

Get Building Integrations with MuleSoft now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.