How to design, implement, and deploy an API with MuleSoft 4
Learn foundational API skills in this step-by-step guide to building a working API using MuleSoft 4, Anypoint Studio, DataWeave, and Anypoint Runtime Manager.
Jul 12, 2024 • 12 Minute Read
Welcome to this step-by-step guide for novice developers seeking to master API development using MuleSoft's robust tools. In this article, you'll learn how to build a Flights API that allows users to retrieve flight details based on origin, destination, and airline.
We’ll design the API in Design Center and implement it in Anypoint Studio using an HTTP listener and database connector. We'll also show you how to transform data with DataWeave before deploying the API using Anypoint Runtime Manager.
We'll also provide essential background information on APIs and best practices for designing, implementing, and deploying them in a way that optimizes connectivity and data transformation. By the end, you'll have a working API and the foundational skills needed to tackle more complex integrations confidently.
Before diving in, you’ll need basic Java programming knowledge and to have Anypoint Studio installed.
Table of contents
Understanding APIs and MuleSoft
APIs (Application Programming Interfaces) are essential connectors that enable different software applications to share data and functionality seamlessly. They act as intermediaries, processing requests and delivering responses based on clearly defined rules. This makes APIs crucial to today's interconnected digital landscape, where applications need to exchange information and interact smoothly.
In the MuleSoft ecosystem, APIs are central to API-led connectivity, an approach that focuses on reusable, modular APIs tailored to specific functions. By dividing integration tasks into system, process, and experience layers, API-led connectivity allows developers to build and manage services that can be adapted across different projects. This modular architecture ensures that changes or updates can be made independently without disrupting other components.
For the Flights API, we'll harness MuleSoft's tools to enable querying flight details based on origin, destination, and airline. We'll design the API using RAML (RESTful API Modeling Language) for clear structure and comprehensive documentation. This design-first approach ensures a consistent, well-defined API that aligns with the API-led connectivity principles.
After building and refining the API design, Anypoint Studio will help bring it to life through connectors and integrations with a PostgreSQL database. DataWeave will transform the retrieved data, while Anypoint Runtime Manager will streamline deployment.
By understanding the concepts of API-led connectivity and modular design, you'll be able to follow the steps to create your API and effectively utilize MuleSoft's tools for scalable integrations.
How to set up Anypoint Studio
Anypoint Studio is MuleSoft's integrated development environment (IDE) designed for API development and integration. To ensure a smooth start, first confirm that Anypoint Studio is properly installed on your machine. If you're new to this IDE, take a moment to familiarize yourself with its user interface, which will be our primary tool for designing and implementing the Flights API.
Installation check
Begin by verifying that Anypoint Studio is installed and running correctly. Open the application and look for the welcome screen, which provides options to create a new project or open an existing one. This screen is also a good point to capture a screenshot for reference.
Navigating the interface
Anypoint Studio’s interface is divided into several key areas:
Package Explorer: Displays your projects and their file hierarchies
Canvas: Where you’ll design your flows visually
Console: Shows output from the application or API you are running
Properties Panel: Allows you to configure the selected element in your flow
Creating a new project
To start building the Flights API:
Choose File > New > Mule Project from the main menu
Enter a Project Name, such as 'FlightsAPI'
Ensure the Runtime dropdown is set to the correct MuleSoft runtime version, which should match the version you are using
Summary
Setting up Anypoint Studio correctly and understanding its layout are crucial first steps in API development. With your environment ready, you’re set to move on to the design and implementation stages of the Flights API.
How to design an API with Design Center
Introduction to Design Center
Design Center is MuleSoft's collaborative environment for designing and documenting APIs. It provides a user-friendly platform for creating API specifications in RAML (RESTful API Modeling Language), which ensures clear and consistent documentation. With features like autocomplete, versioning, and real-time collaboration, it is an essential tool for designing robust APIs quickly.
Key features of Design Center
RAML Autocomplete: Helps autocomplete RAML syntax, minimizing errors and speeding up development
Interactive API Console: Allows testing endpoints directly within the Design Center to verify request and response data
Reusable Components: Lets you define reusable traits, types, and security schemes for modular design
Collaboration: Teams can work on API designs together, sharing real-time feedback
Creating a RAML Specification: Steps for creating and autocompleting a RAML specification
Best practices in API design
Consistency: Use consistent naming conventions and structure
Documentation: Include comprehensive documentation in the RAML file, covering every resource and parameter
Version control: Keep version history to track changes over time
With the API specification ready, you're prepared to move forward with implementation in Anypoint Studio. The Flights API blueprint will serve as the backbone for a seamless integration.
We are in Design Center in order to create a new API, in this case, our Flights API. For that, we have to click on the Create button.
We are going to create a completely new API. Please select New API Specification to establish the behavior of the API and its way of communication with other APIs and systems.
First, we have to name our project. This is called “flightsapi”. Then we will choose to design it on our own.
At this step, it is important for Specification Language to be on RAML 1.0 (RESTful API Modeling Language) because, unlike the previous version 0.8, RAML 1.0 offers significant enhancements, such as modularization through libraries and overlays, data type definitions with advanced inheritance, and improved security schemes. It also supports annotations and response/parameter examples for clearer API documentation.
In contrast, 0.8 is more basic, lacking these advanced features and modularization capabilities. This makes 1.0 a more flexible and powerful choice for designing complex APIs.
Then we click on Create API Spec.
Now we're watching the Designer Canvas:
On the left, we have our Files
On the top center, we have the actual file we are working on
On the bottom, we have Helpers on what we could want to write for auto-generation
We know it’s a RAML API because it says “%RAML” in the first line comment and the version, which is 1.0.
Then we have the title created previously and write the API description, which is what this API will do (in this case, get flights information given an origin and a destination) and define our endpoint /flights:, which describes what we’re going to make HTTP requests to.
Next, we define the verbs, which are methods. We are establishing here the GET method. This means that the following URL is going to accept HTTP GET requests. That specific request is required to have queryParameters, which are the Origin: and Destination:. Those are the origin and destination of the flight. Then we have to define them with values that represent them, like you can see in the example.
Notice that, on the right, the API documentation is being generated, so we don’t have to be concerned about that.
We finish the base API, defining the types and examples of responses as imports that we’ll create in different files for modularization. See that the definition of the type flight, which is our response, is defined at the start of the RAML, such that it is globally accessible to any endpoint, not only the one we are working on. For example, if we wanted to add the endpoint get /flights/{ID}, that endpoint would also return a type flight, so we could reuse it.
Let's define the main response that we will get, which is the 200 OK response. The 200 OK response will have a body, and in that body will be application/json, the content‑type, and the responses, which will be the list of flights.
This is a valid RAML specification of a single endpoint (/flights), single verb (get) API. We finished defining the file base, which auto-saves.
Now that we have the basic scaffolding of our API, let's add the types of the responses. For that, first, we will click on plus, then we will add a file, and we will name it flight.raml. This lets us define the type flight. Notice that the type flight is a data type.
Then we describe the type flight, by defining its type (object) and its properties. The properties ending with a question mark are optional fields.
Now we are creating the file where we’ll define the example responses of the endpoint.
To define several examples, we use a hyphen on the start, which establishes an array of examples.
It’s done! We have a perfectly valid flights API. Now we have to publish it!
To do that, we click on Publish and then Publish to Exchange.
It is now importable from Anypoint Studio.
Implementing and deploying the flights API
We are going to start with a Mule project in Anypoint Studio. Remember that a MuleSoft app is nothing more than a set of operations that happen in a given order to a certain message. That can be decomposed into three operations, in order: an HTTP listener, a database operation, and a transformation.
These three operations are called processors, and within MuleSoft, they represent cards. A flow is just a combination of cards to specify the trigger, what happens with the message once the flow is triggered, and the output.
The first step is to import the API from Exchange. Here we are importing the API by downloading the RAML from Exchange.
When the import is done, the API kit generates all endpoints and methods flows automatically, along with error handling. Notice that it will also autogenerate the HTTP listener configuration. By default, the general path will be /api/*. This means, for example, the /flights endpoint final URL will be http://localhost:8081/api/flights.
Below we're showing the autogenerated global configuration that shows that the port is 8081. To find the global configurations, we need to click the tab named next Global Elements (next to Message Flow).
Now we create a new Mule Configuration File in order to implement the GET method of /flights endpoint.
Let's configure the database connector to connect to the PostgreSQL database.
The first thing to do is upload the JDBC driver to connect to the database. The link to the driver is https://github.com/axel-sirota/MuleSoft4-fundamentals/blob/main/postgresql-42.3.2.jar
The default options are fine.
The next part’s important: We need to point the connector to the database. Fill out the fields as follows:
URL: jdbc:postgres://{host}:{port}/{database}. In our example, we obtained the host from AWS RDS, the port is the default (5432 for postgres), and the database is flights.
Driver class name: Always org.postgresql.Driver
User: The database user (in our case, we use the default postgres)
Password: The password of that username for that database
With this data, we are going to test the connection by clicking Test Connection.
The test connection was successful.
Now, we are ready to process the response of the Database connector by using the DataWeave transformation card.
To make the transformation easier (by joining arrows), we need to load the specification of the response, which is the type flight. We are going to define the flight type based on an example of the file that we downloaded from the API in Exchange, and DataWeave will automatically detect all the fields of the flight type as well as their format.
Another way to define the flight type is by copying the flights.raml file (which we defined in Design Center) in the right panel, and the RAML will specify exactly what the type is.
Now we’re going to join the properties on the left (which are fields from the flights table in the database) with the properties on the right (belonging to the flight type that we just defined).
Now that we’ve created our flow, which is the real implementation of get from /flights, we are going to replace the card auto-generated by the API kit router (which was the fixed transform message) with a flow reference that redirects the response to the flow that we just developed. Then we click play to deploy the app.
We open Postman to test our app. The best way to do it is by importing the API specification in Postman, which will auto-generate all the fields and requests necessary to test the API and therefore the app.
We perform a GET request, setting the origin to LAX and the destination to SFO, and we notice that the response is not the expected one. This is a very common mistake when developing Mule apps. It occured because we didn’t define that the response was an array of flights in DataWeave.
By default, it concatenates the response from each field, so we see all the flight_distance for each flight in a single field instead of different fields for the different flights (which is what we want).
To corroborate this, in the DataWeave card that we implemented, there is a Preview button up to the right. Clicking on it shows an example response and can also verify exactly what we just saw.
To fix this, we have to slightly modify the DataWeave code, defining that the response payload is a map. This is done with the following code:
payload map (payload) -> {
[flight mapping]
}
What we are doing here is defining that the input is a payload and the output is an array of each payload, making the final response an array of flights. We press play again and redeploy.
We test in Postman and now we obtain the correct format, but we are still not filtering by origin nor destination, because the default query taken is “Select * FROM flights”.
The way to fix it is to define the Origin and Destination fields using DataWeave. To do that we are going to add the WHERE statements in the query, escaping the fields ORIGIN_AIRPORT and DESTINATION_AIRPORT, and adding that the value of those fields will be :origin and :destination, fields to be filled by DataWeave. Finally we write the DataWeave code below, in Input Parameters:
{
origin: attributes.queryParams.origin,
destination: attributes.queryParams.destination
}
Finally, we redeploy.
Notice that it actually works.
Finally, we are going to click Deploy to CloudHub by right-clicking on the Mule project.
We log in, and it will automatically be deployed to the Runtime manager.
To conclude, we can see our API deployed. Let's copy the URL and make requests not to localhost, but to the CloudHub URL in Postman.
Notice that it works perfectly. We successfully implemented our API.
Conclusion: Implement sophisticated APIs
API-led connectivity is essential in modern software architecture, enabling modular, scalable, and reusable integrations. In this blog, we've demonstrated how to design, implement, and deploy a Flights API with MuleSoft 4, showing how MuleSoft’s tools—Design Center and Anypoint Studio—streamline the development process.
Design Center helps structure APIs with RAML specifications and provides best practices, while Anypoint Studio seamlessly connects various systems, allowing us to handle HTTP requests and transform data effectively using DataWeave.
Anypoint Platform supports the entire API lifecycle: from design, development, testing, and deployment to monitoring and management. Its modular architecture lets teams focus on specific layers, ensuring rapid development and resilient integrations.
With Anypoint Runtime Manager, deployment is just a click away, providing an integrated environment for managing APIs across environments.
By following these steps, you can confidently leverage MuleSoft’s ecosystem to implement sophisticated APIs that deliver agility, efficiency, and connectivity for your organization's digital transformation goals.
Additional resources: Boost your MuleSoft skills
To deepen your understanding of API design and MuleSoft's capabilities, here are some essential resources that can enhance your learning journey:
Official MuleSoft Documentation: Dive into the comprehensive MuleSoft Documentation for detailed guides on every aspect of the Anypoint Platform, including step-by-step instructions on using Design Center and Anypoint Studio.
MuleSoft Training and Certification: Explore official MuleSoft Training options to gain more structured learning experiences and certification opportunities, perfect for mastering API development and integration with MuleSoft.
MuleSoft 4 Fundamentals: This Pluralsight course provides a thorough introduction to MuleSoft 4, covering everything from the basics to more advanced topics, ideal for both beginners and seasoned developers looking to expand their skills.
MuleSoft Developer Portal: Join the MuleSoft Developer Community to connect with other developers, participate in forums, and access additional learning materials that can help you grow your expertise in API development and management.
These resources offer valuable insights and tools to help you continue your development journey, ensuring you have the knowledge and skills to effectively use MuleSoft’s powerful suite for API-led connectivity.