DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Migrating MuleSoft System API to AWS Lambda (Part 1)
  • Managing Dynamic Application Properties in MuleSoft for CloudHub Applications
  • Using OKTA as Client Provider in Mulesoft
  • Create Proxy Application for Mule APIs

Trending

  • Event-Driven Architectures: Designing Scalable and Resilient Cloud Solutions
  • Immutable Secrets Management: A Zero-Trust Approach to Sensitive Data in Containers
  • Agentic AI for Automated Application Security and Vulnerability Management
  • Medallion Architecture: Why You Need It and How To Implement It With ClickHouse
  1. DZone
  2. Data Engineering
  3. Databases
  4. Build a Mulesoft API Step By Step — Part 1

Build a Mulesoft API Step By Step — Part 1

This blog will take guide you to build a Mulesoft API from scratch step by step. An end-to-end tutorial.

By 
Anupam Chakraborty user avatar
Anupam Chakraborty
DZone Core CORE ·
Jul. 01, 20 · Tutorial
Likes (2)
Comment
Save
Tweet
Share
11.9K Views

Join the DZone community and get the full member experience.

Join For Free

Introduction

Hi All, it has been sometimes I have not come up with any blog. Sorry about that. Today, I thought to write something for the beginners. So, let us get going. Now, MuleSoft claims itself to be the #1 integration and API platform. So, today I will write about a Step-By-Step guide to create a Mule API. This blog would be more for the beginners and those who would like to learn MuleSoft and will walk you through a step by step process of building an API using the various tools and applications provided by MuleSoft at your disposal. If you are already aware of some steps and want to skip some steps, feel free to do so.

I will build an API on a couple of tables in Maria DB. You can use any other backend of your wish with your changes.

So, without any further ado, let us get started with the API building.

Prerequisites

  • Access to the Anypoint Platform. This is also called Cloudhub. You can create your training account for 2 months. You can get the access here <https://anypoint.mulesoft.com/login/signup>
  • Anypoint Studio. I am using the latest version of 7.5. Download it here <https://www.mulesoft.com/lp/dl/studio>
  • Understanding of YAML is good but not necessary.

Step 1: Define the API Contract using RAML

With the API First building approach, the first step in building an API is to create the contract. So, we will take our first step in building the API contract using RAML. MuleSoft supports both RAML and OAS.

To do this we will go to the Anypoint platform and Sign in.

mulesoft

Next, we go to the menu on the top left and select the Design Center.

design center

Click on Create New > Create API specification.

create API

Give a Name and leave other settings as is. We will name this as Mule Demo Database API.

Click Create API Specification.

database API

You will reach the API specification page. Now, this is where we will build our API.

mule demo

Now we do not want to create one monolithic RAML and put everything in there. Instead, I will create some folders and link the various files from there. So, we will create some folder and change some names, and this is what your explorer should look like: 

Now I would start writing my RAML and as an when I have to create any additional files, I will create them. To start with I will create some common traits. These are properties that I would like to put to every endpoint in my API.

Create a file called common-traits.YAML inside the common folder with the following lines

YAML
 




x
25


 
1
handlesAllErrors:
2
 responses:
3
   500:
4
     description: Error response to indicate internal API error.
5
     body:
6
       application/json:
7
         example: 
8
           error: system_exception
9
           description: System Exception Occurred
10
   403:
11
     description: Authentication error response.
12
     body:
13
       application/json:
14
         example: 
15
           error: invalid_client
16
           description: Invalid Client Id or Client Secret
17
           
18
clientIdRequired:
19
 headers:
20
   client_id:
21
     displayName: Client ID
22
     type: string
23
   client_secret:
24
     displayName: Shared Secret
25
     type: string 



I will also create a documentation file inside the documentation folder. This should be a file in markdown language. For now, I will write the file as below

Plain Text
 




xxxxxxxxxx
1


 
1
## Mule Demo Database API
2
 
3
### API Overview
4
This API is only meant for learning and cannot be used in any other way.
5
 
6
##### Copyright
7
anupam@wedointegration.com



At this point, my API in the design would look something like this. design center

Next, let us create some example files. Let us have 2 endpoints. One called /job and the other called /employee. I will create 4 Json in the example folder 2 objects and 2 arrays for each type. I am putting the JSON below, but this is on you as to what data you want.

Job.json

JSON
 




xxxxxxxxxx
1
10


 
1
{
2
 "jobCode" : "J001",
3
 "jobTitle" : "Principal",
4
 "jobDescription" : "Principal",
5
 "minQualification" : "Ph.D",
6
 "empClass" : "Faculty",
7
 "minSalary" : 140000,
8
 "maxSalary" : 190000,
9
 "flsaStatus" : "Salaried (Exempt)"
10
}



Jobs.json

JSON
 




xxxxxxxxxx
1
10


 
1
[{
2
 "jobCode" : "J001",
3
 "jobTitle" : "Principal",
4
 "jobDescription" : "Principal",
5
 "minQualification" : "Ph.D",
6
 "empClass" : "Faculty",
7
 "minSalary" : 140000,
8
 "maxSalary" : 190000,
9
 "flsaStatus" : "Salaried (Exempt)"
10
}]


 

Employee.json

JSON
 




xxxxxxxxxx
1
13


 
1
{
2
   "empId" : "E00001",
3
   "nationalIDNumber" : "111-11-1111",
4
   "eName" : "Mr Jon Doe",
5
   "addressLn" : "1 Area",
6
   "addressCity" : "Atlanta",
7
   "addressZIP" : "30303",
8
   "addressState" : "GA",
9
   "addressCountry" : "USA",
10
   "phone" : "9999999999",
11
   "gender" : "Male",
12
   "birthDate" : "1977-01-19"
13
}


 

Employees.json

JSON
 




xxxxxxxxxx
1
13


 
1
[{
2
   "empId" : "E00001",
3
   "nationalIDNumber" : "111-11-1111",
4
   "eName" : "Mr Jon Doe",
5
   "addressLn" : "1 Area",
6
   "addressCity" : "Atlanta",
7
   "addressZIP" : "30303",
8
   "addressState" : "GA",
9
   "addressCountry" : "USA",
10
   "phone" : "9999999999",
11
   "gender" : "Male",
12
   "birthDate" : "1977-01-19"
13
}]


 

Now we would need to create the schema in RAML format. I will create 2 schema files, one for the employee and one for the job. They would like as below: 

Job.schema

JSON
 




xxxxxxxxxx
1
11


 
1
#%RAML 1.0 DataType
2
type: object
3
properties:
4
jobCode: string
5
jobTitle: string
6
jobDescription: string
7
minQualification: string
8
empClass: string
9
minSalary: number
10
maxSalary: number
11
 flsaStatus: string


 

Employee.schema

JSON
 




xxxxxxxxxx
1
24


 
1
#%RAML 1.0 DataType
2
type: object
3
properties:
4
 empId: 
5
  type: string
6
  minLength: 5
7
 nationalIDNumber: 
8
  type: string
9
  minLength: 9
10
  maxLength: 9
11
 eName: string
12
 addressLn: string
13
 addressCity: string
14
 addressZIP: string
15
 addressState: string
16
 addressCountry: string
17
 phone: string
18
 gender:
19
  type: string
20
  enum:
21
   - Male
22
   - Female
23
 birthDate:
24
  type: date-only



Finally coming back to my API, I will now create all the necessary endpoints.

In this case, I will have 4 endpoints, GET, and POST for each employee and job. You can add other endpoints like PUT, DELETE or PATCH, etc. 

Once you are done with the API, it should look like this.

JSON
 




xxxxxxxxxx
1
66


 
1
#%RAML 1.0
2
title: Mule Demo Database API
3
version: 1.0
4
protocols: [ HTTPS ]
5
mediaType: application/json
6
 
7
traits: !include common/common-traits.yaml
8
baseUri: http://localhost:8081/api/
9
 
10
documentation:
11
 - title: Mule Demo Database API.
12
   content: !include documentation/doc.md
13
 
14
types:
15
 employee: !include schema/employee.raml
16
 job: !include schema/job.raml
17
 
18
/employee:
19
 post:
20
   is: [handlesAllErrors,clientIdRequired]
21
   description: Create new Employee
22
   body:
23
     application/json:
24
       example: !include example/employees.json
25
       type: employee[]
26
   responses:
27
     200:
28
       body:
29
         application/json:
30
           example:
31
             status: success
32
 /{empId}:
33
   get:
34
     is: [handlesAllErrors, clientIdRequired]
35
     description:   Get employee with employee Id.
36
     responses:
37
       200:
38
         body:
39
           application/json:
40
             example: !include example/employee.json
41
             type: employee
42
 
43
/job:
44
 post:
45
   is: [handlesAllErrors,clientIdRequired]
46
   description: Create new Job
47
   body:
48
     application/json:
49
       example: !include example/jobs.json
50
       type: job[]
51
   responses:
52
     200:
53
       body:
54
         application/json:
55
           example:
56
             status: success
57
 /{jobCode}:
58
   get:
59
     is: [handlesAllErrors, clientIdRequired]
60
     description:   Get Job by Job Code.
61
     responses:
62
       200:
63
         body:
64
           application/json:
65
             example: !include example/job.json
66
             type: job



Now, you can immediately, click on the Mocking Service at the Right top corner and your services are up and running. This is what you can call from the Postman or any other Rest Client.

anypoint

This completes our step 1 which would now take us to the second step of importing this API into our Studio and starting to write the interface.

Step 2: Import the API into Anypoint Studio

 As for Step 2, We will switch on the Anypoint Studio and select a workspace where all our Mule Project will be stored.

anypoint studio launcher

Now select Create a Mule Project or click on File > New > Mule Project.

Give the project a name. Note here you cannot put a name with space. I will use mule-demo-database-app. Now in the API Implementation window, select Import From Design Center.

project settings

Click the browse button and a popup window will come asking for your credentials. Give the credentials which you used to login to Cloudhub. Note that you can deploy this application later into another Cloudhub or customer. This does not make a connection to the API, it simply pulls down the API to your application.

This should take you to a Browse Window where you should be able to see all APIs created in the design center of this account.

mule demo 

Click on the API which you created and click OK. If there is no error in your API you should see a Green Tick mark saying you are importing the following API.

mule demo database

Now click Finish and your API will be scaffolded, and the Skeleton Application will be automatically created for you.

api

This would now help you in the implementation of your API as per your need. If just at this point, you do run your application, you should be able to test your application with the dummy data. 

Click on Run > Run > Run as Mule Application.

Your application will be deployed in the Mule runtime embedded in the Anypoint Studio and you can go to a browser and go to the endpoint http://localhost:8081/console to test your application. You should see a screen like this where you can TEST your application. Note, for now, you can use anything in client id and secret since the application does not verify the client authentication.

Now let us start building the API Implementation to execute the back-end code for this API.

Step 3: Build the API Implementation

In this step, we would create the Application Implementation. Before moving ahead, I like to create 3 files in the code. Go to the folder src/main/mule. Right-click > New > Mule Configuration File and type "global". Same way create a file for employee and job each. The global file will hold all global configurations whereas the job and employee should hold implementation for each of the individual endpoints. Move the Global Elements HTTP Listener Config and Router into the global.xml file.

After this, your workspace should look like this.

package explorer

Now I will create the connectivity to my back end Maria DB using a database connector. The database here is in AWS so, it will be accessible from my computer as well as from the cloudhub. Note that if you have a local database, you may not be able to access it from the cloudhub.

Following are the content of each file

Global.xml

XML
 




xxxxxxxxxx
1
20


 
1
<?xml version="1.0" encoding="UTF-8"?>
2
 
3
<mule xmlns:db="http://www.mulesoft.org/schema/mule/db"
4
    xmlns:mongo="http://www.mulesoft.org/schema/mule/mongo"
5
    xmlns:apikit="http://www.mulesoft.org/schema/mule/mule-apikit" xmlns:http="http://www.mulesoft.org/schema/mule/http"
6
    xmlns="http://www.mulesoft.org/schema/mule/core"
7
    xmlns:doc="http://www.mulesoft.org/schema/mule/documentation" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="
8
http://www.mulesoft.org/schema/mule/mule-apikit http://www.mulesoft.org/schema/mule/mule-apikit/current/mule-apikit.xsd 
9
http://www.mulesoft.org/schema/mule/http http://www.mulesoft.org/schema/mule/http/current/mule-http.xsd http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd
10
http://www.mulesoft.org/schema/mule/mongo http://www.mulesoft.org/schema/mule/mongo/current/mule-mongo.xsd
11
http://www.mulesoft.org/schema/mule/db http://www.mulesoft.org/schema/mule/db/current/mule-db.xsd">
12
 
13
    <http:listener-config name="api-httpListenerConfig">
14
       <http:listener-connection host="0.0.0.0" port="8081" />
15
   </http:listener-config>
16
   <apikit:config name="api-config" api="api.raml" outboundHeadersMapName="outboundHeaders" httpStatusVarName="httpStatus" />
17
    <db:config name="Database_Config" doc:name="Database Config" doc:id="42b3d660-c98f-481f-a478-7b9f57978bfd" >
18
         <db:my-sql-connection host="*.*.*.*" port="3306" user="****" password="***" database="demo" />
19
    </db:config>
20
</mule>


 

Api.xml

XML
 




xxxxxxxxxx
1
165


 
1
<?xml version="1.0" encoding="UTF-8"?>
2
<mule xmlns:doc="http://www.mulesoft.org/schema/mule/documentation" xmlns="http://www.mulesoft.org/schema/mule/core" xmlns:apikit="http://www.mulesoft.org/schema/mule/mule-apikit" xmlns:http="http://www.mulesoft.org/schema/mule/http" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd http://www.mulesoft.org/schema/mule/http http://www.mulesoft.org/schema/mule/http/current/mule-http.xsd http://www.mulesoft.org/schema/mule/mule-apikit http://www.mulesoft.org/schema/mule/mule-apikit/current/mule-apikit.xsd ">
3
   <flow name="api-main">
4
       <http:listener config-ref="api-httpListenerConfig" path="/api/*">
5
           <http:response statusCode="#[vars.httpStatus default 200]">
6
               <http:headers>#[vars.outboundHeaders default {}]</http:headers>
7
           </http:response>
8
           <http:error-response statusCode="#[vars.httpStatus default 500]">
9
               <http:body>#[payload]</http:body>
10
               <http:headers>#[vars.outboundHeaders default {}]</http:headers>
11
           </http:error-response>
12
       </http:listener>
13
       <apikit:router config-ref="api-config" />
14
       <error-handler>
15
           <on-error-propagate type="APIKIT:BAD_REQUEST">
16
               <ee:transform xmlns:ee="http://www.mulesoft.org/schema/mule/ee/core" xsi:schemaLocation="http://www.mulesoft.org/schema/mule/ee/core http://www.mulesoft.org/schema/mule/ee/core/current/mule-ee.xsd">
17
                   <ee:message>
18
                       <ee:set-payload><![CDATA[%dw 2.0
19
output application/json
20
---
21
{message: "Bad request"}]]></ee:set-payload>
22
                   </ee:message>
23
                   <ee:variables>
24
                       <ee:set-variable variableName="httpStatus">400</ee:set-variable>
25
                   </ee:variables>
26
               </ee:transform>
27
           </on-error-propagate>
28
           <on-error-propagate type="APIKIT:NOT_FOUND">
29
               <ee:transform xmlns:ee="http://www.mulesoft.org/schema/mule/ee/core" xsi:schemaLocation="http://www.mulesoft.org/schema/mule/ee/core http://www.mulesoft.org/schema/mule/ee/core/current/mule-ee.xsd">
30
                   <ee:message>
31
                       <ee:set-payload><![CDATA[%dw 2.0
32
output application/json
33
---
34
{message: "Resource not found"}]]></ee:set-payload>
35
                   </ee:message>
36
                   <ee:variables>
37
                       <ee:set-variable variableName="httpStatus">404</ee:set-variable>
38
                   </ee:variables>
39
               </ee:transform>
40
           </on-error-propagate>
41
           <on-error-propagate type="APIKIT:METHOD_NOT_ALLOWED">
42
               <ee:transform xmlns:ee="http://www.mulesoft.org/schema/mule/ee/core" xsi:schemaLocation="http://www.mulesoft.org/schema/mule/ee/core http://www.mulesoft.org/schema/mule/ee/core/current/mule-ee.xsd">
43
                   <ee:message>
44
                       <ee:set-payload><![CDATA[%dw 2.0
45
output application/json
46
---
47
{message: "Method not allowed"}]]></ee:set-payload>
48
                   </ee:message>
49
                   <ee:variables>
50
                       <ee:set-variable variableName="httpStatus">405</ee:set-variable>
51
                   </ee:variables>
52
               </ee:transform>
53
           </on-error-propagate>
54
           <on-error-propagate type="APIKIT:NOT_ACCEPTABLE">
55
               <ee:transform xmlns:ee="http://www.mulesoft.org/schema/mule/ee/core" xsi:schemaLocation="http://www.mulesoft.org/schema/mule/ee/core http://www.mulesoft.org/schema/mule/ee/core/current/mule-ee.xsd">
56
                   <ee:message>
57
                       <ee:set-payload><![CDATA[%dw 2.0
58
output application/json
59
---
60
{message: "Not acceptable"}]]></ee:set-payload>
61
                   </ee:message>
62
                   <ee:variables>
63
                       <ee:set-variable variableName="httpStatus">406</ee:set-variable>
64
                   </ee:variables>
65
               </ee:transform>
66
           </on-error-propagate>
67
           <on-error-propagate type="APIKIT:UNSUPPORTED_MEDIA_TYPE">
68
               <ee:transform xmlns:ee="http://www.mulesoft.org/schema/mule/ee/core" xsi:schemaLocation="http://www.mulesoft.org/schema/mule/ee/core http://www.mulesoft.org/schema/mule/ee/core/current/mule-ee.xsd">
69
                   <ee:message>
70
                       <ee:set-payload><![CDATA[%dw 2.0
71
output application/json
72
---
73
{message: "Unsupported media type"}]]></ee:set-payload>
74
                   </ee:message>
75
                   <ee:variables>
76
                       <ee:set-variable variableName="httpStatus">415</ee:set-variable>
77
                   </ee:variables>
78
               </ee:transform>
79
           </on-error-propagate>
80
           <on-error-propagate type="APIKIT:NOT_IMPLEMENTED">
81
               <ee:transform xmlns:ee="http://www.mulesoft.org/schema/mule/ee/core" xsi:schemaLocation="http://www.mulesoft.org/schema/mule/ee/core http://www.mulesoft.org/schema/mule/ee/core/current/mule-ee.xsd">
82
                   <ee:message>
83
                       <ee:set-payload><![CDATA[%dw 2.0
84
output application/json
85
---
86
{message: "Not Implemented"}]]></ee:set-payload>
87
                   </ee:message>
88
                   <ee:variables>
89
                       <ee:set-variable variableName="httpStatus">501</ee:set-variable>
90
                   </ee:variables>
91
               </ee:transform>
92
           </on-error-propagate>
93
       </error-handler>
94
   </flow>
95
   <flow name="api-console">
96
       <http:listener config-ref="api-httpListenerConfig" path="/console/*">
97
           <http:response statusCode="#[vars.httpStatus default 200]">
98
               <http:headers>#[vars.outboundHeaders default {}]</http:headers>
99
           </http:response>
100
           <http:error-response statusCode="#[vars.httpStatus default 500]">
101
               <http:body>#[payload]</http:body>
102
               <http:headers>#[vars.outboundHeaders default {}]</http:headers>
103
           </http:error-response>
104
       </http:listener>
105
       <apikit:console config-ref="api-config" />
106
       <error-handler>
107
           <on-error-propagate type="APIKIT:NOT_FOUND">
108
               <ee:transform xmlns:ee="http://www.mulesoft.org/schema/mule/ee/core" xsi:schemaLocation="http://www.mulesoft.org/schema/mule/ee/core http://www.mulesoft.org/schema/mule/ee/core/current/mule-ee.xsd">
109
                   <ee:message>
110
                       <ee:set-payload><![CDATA[%dw 2.0
111
output application/json
112
---
113
{message: "Resource not found"}]]></ee:set-payload>
114
                   </ee:message>
115
                   <ee:variables>
116
                       <ee:set-variable variableName="httpStatus">404</ee:set-variable>
117
                   </ee:variables>
118
               </ee:transform>
119
           </on-error-propagate>
120
       </error-handler>
121
   </flow>
122
   <flow name="get:\employee\(empId):api-config">
123
       <ee:transform xmlns:ee="http://www.mulesoft.org/schema/mule/ee/core">
124
           <ee:variables>
125
               <ee:set-variable variableName="empId">attributes.uriParams.'empId'</ee:set-variable>
126
           </ee:variables>
127
       </ee:transform>
128
         <flow-ref doc:name="employeeGet" doc:id="20d66a4d-dcff-40d9-81a9-9ef640322b2a" name="employeeGet"/>
129
   </flow>
130
   <flow name="get:\job\(jobCode):api-config">
131
       <ee:transform xmlns:ee="http://www.mulesoft.org/schema/mule/ee/core">
132
           <ee:variables>
133
               <ee:set-variable variableName="jobCode">attributes.uriParams.'jobCode'</ee:set-variable>
134
           </ee:variables>
135
       </ee:transform>
136
         <flow-ref doc:name="jobGet" doc:id="c442aa02-8a16-4285-bc99-742b7fb24879" name="jobGet"/>
137
   </flow>
138
   <flow name="post:\employee:application\json:api-config">
139
       <flow-ref doc:name="employeeInsert" doc:id="960c1677-7334-4b0e-91ff-31137ec865c7" name="employeeInsert"/>
140
         <ee:transform xmlns:ee="http://www.mulesoft.org/schema/mule/ee/core" xsi:schemaLocation="http://www.mulesoft.org/schema/mule/ee/core http://www.mulesoft.org/schema/mule/ee/core/current/mule-ee.xsd">
141
           <ee:message>
142
               <ee:set-payload><![CDATA[%dw 2.0
143
output application/json
144
---
145
{
146
 status: "success"
147
}]]></ee:set-payload>
148
           </ee:message>
149
       </ee:transform>
150
   </flow>
151
   <flow name="post:\job:application\json:api-config">
152
       <flow-ref doc:name="jobInsert" doc:id="739a32c6-0e36-45fd-8f8c-9f8416d50c86" name="jobInsert"/>
153
         <ee:transform xmlns:ee="http://www.mulesoft.org/schema/mule/ee/core" xsi:schemaLocation="http://www.mulesoft.org/schema/mule/ee/core http://www.mulesoft.org/schema/mule/ee/core/current/mule-ee.xsd">
154
           <ee:message>
155
               <ee:set-payload><![CDATA[%dw 2.0
156
output application/json
157
---
158
{
159
 status: "success"
160
}]]></ee:set-payload>
161
           </ee:message>
162
       </ee:transform>
163
   </flow>
164
</mule>
165

          


 

Employee.xml

XML
 




xxxxxxxxxx
1
63


 
1
<?xml version="1.0" encoding="UTF-8"?>
2
 
3
<mule xmlns:db="http://www.mulesoft.org/schema/mule/db" xmlns:ee="http://www.mulesoft.org/schema/mule/ee/core"
4
    xmlns:mongo="http://www.mulesoft.org/schema/mule/mongo"
5
    xmlns="http://www.mulesoft.org/schema/mule/core" xmlns:doc="http://www.mulesoft.org/schema/mule/documentation" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd
6
http://www.mulesoft.org/schema/mule/mongo http://www.mulesoft.org/schema/mule/mongo/current/mule-mongo.xsd
7
http://www.mulesoft.org/schema/mule/ee/core http://www.mulesoft.org/schema/mule/ee/core/current/mule-ee.xsd
8
http://www.mulesoft.org/schema/mule/db http://www.mulesoft.org/schema/mule/db/current/mule-db.xsd">
9
 
10
    <flow name="employeeInsert" doc:id="5265fa9b-6f54-4f7c-8cdd-87642ee588b0" >
11
         <ee:transform doc:name="Transform Message" doc:id="d40b196b-fa52-4bc6-81b3-cbd838baf0ff" >
12
              <ee:message >
13
                    <ee:set-payload ><![CDATA[%dw 2.0
14
output application/json
15
---
16
{
17
    query: "insert into employee (empId,nationalIDNumber,eName,addressLn,addressCity,addressZIP,addressState,addressCountry,phone,gender,birthDate) 
18
              values (:empId,:nationalIDNumber,:eName,:addressLn,:addressCity,:addressZIP,:addressState,:addressCountry,:phone,:gender,:birthDate)",
19
    body: payload map ( payload01 , indexOfPayload01 ) -> {
20
              empId: payload01.empId,
21
              nationalIDNumber: payload01.nationalIDNumber,
22
              eName: payload01.eName,
23
              addressLn: payload01.addressLn,
24
              addressCity: payload01.addressCity,
25
              addressZIP: payload01.addressZIP,
26
              addressState: payload01.addressState,
27
              addressCountry: payload01.addressCountry,
28
              phone: payload01.phone,
29
              gender: payload01.gender,
30
              birthDate: payload01.birthDate
31
    }
32
}]]></ee:set-payload>
33
              </ee:message>
34
         </ee:transform>
35
         <db:bulk-insert doc:name="Bulk insert" doc:id="0736fde4-aff5-405d-8d34-bd40f644baec" config-ref="Database_Config">
36
              <db:bulk-input-parameters ><![CDATA[#[payload.body]]]></db:bulk-input-parameters>
37
              <db:sql ><![CDATA[#[payload.query]]]></db:sql>
38
         </db:bulk-insert>
39
         <logger level="INFO" doc:name="Logger" doc:id="c30da949-db08-471a-bc57-65d9b5b7dcf2" message="Insert of Data Complete"/>
40
    </flow>
41
    <flow name="employeeGet" doc:id="8380dba3-0eb4-4aa9-bfb4-182e8cc8a689" >
42
         <ee:transform doc:name="Transform Message" doc:id="61716d39-89f2-41b8-9b18-17f8945a2b76" >
43
              <ee:message >
44
                    <ee:set-payload ><![CDATA[%dw 2.0
45
output application/java
46
---
47
"select * from employee where empId = '" ++ vars.empId ++ "'"]]></ee:set-payload>
48
              </ee:message>
49
         </ee:transform>
50
         <db:select doc:name="Select" doc:id="9ef1e38a-e8d5-4740-9798-05e6634a852f" config-ref="Database_Config">
51
              <db:sql ><![CDATA[#[payload]]]></db:sql>
52
         </db:select>
53
         <ee:transform doc:name="Transform Message" doc:id="9d48be5a-7a19-4adc-b4b6-e53e65ce7d21" >
54
              <ee:message >
55
                    <ee:set-payload ><![CDATA[%dw 2.0
56
output application/json
57
---
58
payload[0] default {}]]></ee:set-payload>
59
              </ee:message>
60
         </ee:transform>
61
         <logger level="INFO" doc:name="Logger" doc:id="935042a6-83b8-4ba6-9723-e61bd61ce515" message='#["Got Data for " ++ (payload.eName default "None")]'/>
62
    </flow>
63
</mule>


 

Job.xml

XML
 




xxxxxxxxxx
1
63


 
1
<?xml version="1.0" encoding="UTF-8"?>
2
 
3
<mule xmlns:db="http://www.mulesoft.org/schema/mule/db"
4
    xmlns:ee="http://www.mulesoft.org/schema/mule/ee/core"
5
    xmlns="http://www.mulesoft.org/schema/mule/core" xmlns:doc="http://www.mulesoft.org/schema/mule/documentation"
6
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
7
    xsi:schemaLocation="
8
http://www.mulesoft.org/schema/mule/db http://www.mulesoft.org/schema/mule/db/current/mule-db.xsd 
9
http://www.mulesoft.org/schema/mule/ee/core http://www.mulesoft.org/schema/mule/ee/core/current/mule-ee.xsd http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd">
10
 
11
    <flow name="jobInsert" doc:id="e136c434-10be-4b46-8043-57344343ccaa" >
12
         <ee:transform doc:name="Transform Message" doc:id="096c0ad4-3f35-4cb9-b180-1bcbe2f73061" >
13
              <ee:message >
14
                    <ee:set-payload ><![CDATA[%dw 2.0
15
output application/json
16
---
17
{
18
    query: "insert into job (jobCode,jobTitle,jobDescription,minQualification,empClass,minSalary,maxSalary,flsaStatus) 
19
              values (:jobCode,:jobTitle,:jobDescription,:minQualification,:empClass,:minSalary,:maxSalary,:flsaStatus)",
20
    body: payload map ( payload01 , indexOfPayload01 ) -> {
21
              jobCode: payload01.jobCode,
22
              jobTitle: payload01.jobTitle,
23
              jobDescription: payload01.jobDescription,
24
              minQualification: payload01.minQualification,
25
              empClass: payload01.empClass,
26
              minSalary: payload01.minSalary,
27
             maxSalary: payload01.maxSalary,
28
              flsaStatus: payload01.flsaStatus
29
    }
30
}]]></ee:set-payload>
31
              </ee:message>
32
         </ee:transform>
33
         <db:bulk-insert doc:name="Bulk insert" doc:id="8f2a4472-997e-45c9-8e21-1d6f39a4c4f4" config-ref="Database_Config">
34
              <db:bulk-input-parameters ><![CDATA[#[payload.body]]]></db:bulk-input-parameters>
35
              <db:sql ><![CDATA[#[payload.query]]]></db:sql>
36
         </db:bulk-insert>
37
         <logger level="INFO" doc:name="Logger" doc:id="dede0e83-c71b-443b-92ed-9d51fc74a1d0" message="Insert of Data Complete"/>
38
    </flow>
39
    
40
    <flow name="jobGet" doc:id="ff4dc4f5-8532-4493-a569-cbfd448e8da4" >
41
         <ee:transform doc:name="Transform Message" doc:id="b8ee96a1-1fc7-48d2-80bb-bfae7b660b04" >
42
              <ee:message >
43
                    <ee:set-payload ><![CDATA[%dw 2.0
44
output application/java
45
---
46
"select * from job where jobCode = '" ++ vars.jobCode ++ "'"]]></ee:set-payload>
47
              </ee:message>
48
         </ee:transform>
49
         <db:select doc:name="Select" doc:id="201fdc74-0c7d-43bf-be23-296a49f1cfc5" config-ref="Database_Config">
50
              <db:sql ><![CDATA[#[payload]]]></db:sql>
51
         </db:select>
52
         <ee:transform doc:name="Transform Message" doc:id="2ee13a23-eddd-47af-a57b-c1bac01e005b" >
53
              <ee:message >
54
                    <ee:set-payload ><![CDATA[%dw 2.0
55
output application/json
56
---
57
payload[0] default {}]]></ee:set-payload>
58
              </ee:message>
59
         </ee:transform>
60
         <logger level="INFO" doc:name="Logger" doc:id="370287ca-2405-470f-b414-e73158160a28" message='#["Got Data for " ++ (payload.jobTitle default "None")]'/>
61
    </flow>  
62
</mule>
63
 


 

Go ahead and again run the application and you should be able to go to the console in http://localhost:8081/console and you should be able to test all the endpoints that we created.

Step 4: Deploy the API into Cloudhub and Test 

As the last step, we will deploy this application into Cloudhub and run the endpoint. There are various ways to deploy the application into Cloudhub like using the maven or CI/CD pipeline. But we will simply deploy the app using Studio.

deploy to cloudhub

It should ask you a couple of information. For now, we will just put the application name with a suffix for the environment and deploy the app.

runtime manager

We can now go to the Cloudhub to check the status of our app. Once it is deployed it should look something like this:

runtime manager

Click on the app name and you should see various details. We need the domain name as mentioned below in blue.

mule-demo

Navigate to a web browser and use the endpoint HTTP://<domainname>/console. This should take you to the same Console as above and you will be able to test out the application. API console

With this, we come to the end of this blog. If you see this page, it says the application is not secure, this is because we have used HTTP and not HTTPS as our listener. In my next blog, I will write how to use the make the application secure and get more out of API Manager.

For more blogs like this and the application that I built, please visit https://www.wedointegration.com/post.php?posturl=build_a_mulesoft_api_step_by_step_part_1. Also, you can find the Github link there.

API application Continuous Integration/Deployment MuleSoft Database JSON

Published at DZone with permission of Anupam Chakraborty. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Migrating MuleSoft System API to AWS Lambda (Part 1)
  • Managing Dynamic Application Properties in MuleSoft for CloudHub Applications
  • Using OKTA as Client Provider in Mulesoft
  • Create Proxy Application for Mule APIs

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!