Building a RESTful API using MuleSoft
Introduction
MuleSoft is a popular integration platform that has recently seen exponential growth in usage, and rightfully so — the platform has a lot to offer and I’m excited to share some of its capabilities with you today. If you haven’t had experience with MuleSoft yet I am confident that, after reading this blog, you’ll be eager to try your hand at it.
If you’re wondering why you should choose MuleSoft over other platforms; here are a couple of reasons.
Development Cycle — MuleSoft allows you to design, implement, and manage your APIs all in one platform.
Reduced Development Time — MuleSoft promises to eliminate the “donkey work” of data integration (hence the name) and by removing the boiler plate work the development time is optimized and your services can be up and running in no time. Just wait and see for yourself.
Built on XML — Unlike other no and low-code platforms, MuleSoft is built on XML that you can view, edit, and fully develop in if you please. Having the choice between the graphical interface and XML, or even a combination of the two is a huge advantage.
These are just a few of the many advantages that MuleSoft has to offer but at this point, I will let the work do the talking so let’s go ahead and jump in to the tutorial.
In this tutorial, I want to walk you through developing a RESTful API from start to finish using MuleSoft. We will start by designing the RAML of our service, publishing it to MuleSoft’s open-source community and finally implementing each one of our endpoints.
For this tutorial, I will be using the JSONPlaceholder service, which they describe as a “free fake API service for testing and prototyping”. This is an awesome resource that allows you to implement any of the HTTP methods on the given fake data.
We will implement the following HTTP methods using the /comments resource of the JSONplaceholder service.
- GET /comments
- POST /comments
- PUT /comments/{postId}
Before we begin,
Pre-requisites
- Anypoint Platform account — if you don’t already have one you can make one here.
- Anypoint Studio downloaded on your device — you can download it here.
- Familiarity with MuleSoft’s core components — learn more here.
Now we’re ready and can get started!
Part 1. Design your RAML using Design Center
The first step to building a service is designing the RAML. In MuleSoft, you do this in Design Center.
To access Design Center, log in to your MuleSoft Anypoint account and click on Start Designing which you should see on the home page. Then click Create New and choose the New API Spec option. Go ahead and give your API a title.
Once you have created your API Spec you should land on an empty RAML which is known as your root file.
We will start by defining a GET method for the /comments resource. For now, leave the data and example fields blank we will define them later.
Once you’ve defined your GET method, create a folder called examples using the + button to the left of the screen and add a file called CommentArray.json and another called Comment.json.
In each file, respectively, we will add the appropriate json structures.
Next, create a folder for datatypes and add a new file called CommentDataType.raml. Make sure to specify the file as a RAML Data Type and once you create the file, go ahead and define the data type.
Now back in the root RAML, add a comment type to the top of the RAML and add the path to the comment type we have defined. Next, add the datatype and example to the GET method.
Once we have a fully defined GET method we can move on to the POST and PUT methods. Once those are complete, your finished RAML should look something like this.
After building the RAML, you will want to publish it to Exchange to begin development in Anypoint Studio. To publish to Exchange, just click the blue Publish button on the top right side of the screen and choose the Publish to Exchange option.
You will be asked to add what asset and API version you are publishing — see below.
Note, any time you make changes to your design after publishing to Exchange you will have to re-publish and update your asset version.
Once the API design is successfully published you are all set for Part 1, congratulations! You are now ready to move on to implementation.
Part 2: Implement your APIs using Anypoint Studio
Anypoint Studio is MuleSoft’s IDE and is built on Eclipse, so you might already be familiar with it. We will be using it to develop our APIs, so the first thing you want to do is open up your Anypoint Studio on your device.
Then, we will go ahead and import our API design from Exchange.
To import from Exchange, you have to be logged into your Anypoint platform account in Studio. To log in, go to Preferences → Anypoint Studio → Authentication and add your account.
Now let’s go ahead and import our design from Exchange. To do so, go to File → New → Mule Project and a window should pop up.
In the window, add your project name and then press the green + under the Import a published API tab and choose the from Exchange option. Search for your API design and add it. Finally, make sure that the Scaffold flows from these API specifications is checked and then press Finish.
Before we move on, I want to talk about what the scaffold flows check will do for us. Remember how I mentioned earlier that MuleSoft promises to eliminate the boiler plate work? Well this is one way they do that. By checking this box we are telling MuleSoft to use APIKit.
What exactly is APIkit? APIkit will generate a flow for each HTTP method you have defined in your RAML — essentially building out a template for you before you even start implementation. So let’s go ahead and see what that looks like.
Once the project is built, you should see something that looks like this in your source .xml file.
The first two flows are your standard APIkit flows — the APIkit Router validates the requests against the RAML and routes them to the appropriate flow while the APIkit Console gives you access to the generated documentation for the API. After these two flows, the other three are for each one of the HTTP methods we defined in our RAML — GET, POST, PUT.
We will begin our development by first renaming this file to interface.xml and then creating a new Mule Configuration File called implementation.xml in which we will develop each one of our HTTP methods. The first one being GET comments.
In your interface.xml, right click on the Transform Message component in your GET comments flow and choose Extract to → Flow. Go ahead and name your flow and make sure you extract it to your implementation configuration file and not the current one.
Now switch to your implementation configuration file and from the HTTP Module in the Mule Palette on the right side of your screen drag a Request component before your Transform Message. Before we fill out the request component we need to set up a global configuration for it.
To do this we will start by creating a config-common.yaml in src/main/resources and in it we will define the http port and resource url.
Then we will create a new Mule Configuration file and call it global. In global.xml switch from Message Flow view to Global Elements and press the blue Create button.
We will first create a Configuration properties element from Global Configurations in which we will point to our config-common.yaml.
Next we will create another global element by choosing HTTP Request configuration from Connector Configuration. Add the protocol, host, and port using the system variables defined in config-common.yaml. This is what the XML for your new global variable should look like.
Note, to view the XML switch from the Global Elements perspective to the Configuration XML perspective.
Now that we have set up our HTTP Request configuration we can go back to implementation.xml and finish building the HTTP Request by specifying the configuration, ensuring the method is GET, and adding a path.
We can go ahead and delete the Transform Message component now and instead add Set Payload and Set Variable components, which you will find in the Core module of the Mule Palette.
We don’t need to edit the Set Payload component as the default value is just the payload, which is what we want returned for our GET method. However, for the Set Variable component we will add a variable named httpStatus and a value of 200.
This is what your final XML for the getComments flow will look like.
At this point we have the bare minimum of a fully functional GET comments flow. To make sure that it works, we will go ahead and run the application by right clicking on the project directory and choosing Run as → Mule Application (configure) and ensuring that the right project is selected. Once the project successfully deploys, the APIkit Console Window on the left side of your screen should show an Open console button. Go ahead and click that.
You should be directed to a page that looks something like this.
Now let’s go ahead and make sure that our endpoint works by pressing the GET method and then hitting Send. You should get a 200 response along with the comments data.
This means we have successfully built and tested our first endpoint. Now let’s go ahead and repeat the process for the POST and PUT methods. The only difference being making sure you specify the correct method in your HTTP Requests and for the PUT method, including the URI in the request. Also, you will want to move the content of your Transform Messages to your Set Payload component since we will want to return a response instead of data.
Once you’re done, your implementation.xml should look something like this.
Don’t forget to test these methods to make sure they run successfully.
Once you do that, you are officially done implementing your flows and have your first MuleSoft REST API ready to go!
Note, while error handling is not discussed in this post, it is an integral part of development and should always be considered. To learn more about how to handle errors on MuleSoft check out their documentation here.
Conclusion
I hope this tutorial gave you some insight on how quickly you and your team can have your services up and running with MuleSoft and has inspired you to play around with all that MuleSoft has to offer!
Feel free to check out the rest of the project code here.