HTTP Query Parameters from JSON
Use case
When integrating with an HTTP or REST API, it is common to set query parameters for API requests. In scenarios where JSON data is in Exchange, specific values from the JSON may need to be extracted and used as query parameters in subsequent HTTP requests. This process involves parsing the JSON to retrieve the necessary values and then incorporating these values into the query string of the HTTP request to ensure proper communication and data retrieval from the API.
Below is an example of the data in Exchange:
In this example, we will call a service that estimates the age based on a single name:
For basic usage, you just need to pass a firsName
from our JSON as the name
parameter in HTTP service. The service will process the request and return an estimated age for the given name.
Implementation Highlights:
- Unmarshall JSON to Dynamic Java Object: Use Jackson to convert JSON data to a dynamic Java object, leveraging Jackson's dynamic binding capabilities.
- Set Query Parameter: Define query paramatest using Exchange variables.
- Call HTTP Service: Call HTTP Service using defined query parameters
Design
In the following example, we demonstrate how to create an Exchange that starts with a time-based trigger (repeats once) and sets query parameters for an HTTP request using values extracted from a JSON response.
- Set JSON Example: We start by setting our JSON example to a variable called
json
. - Unmarshall JSON to Java Object: The JSON data is unmarshalled into a Java object stored in a variable named
data
. - Set Header CamelHttpQuery: This is a crucial step where we set the
CamelHttpQuery
header using Groovy expression language, with values extracted from thedata
variable. - Call HTTP Service: An HTTP service is called using the HTTP component.
- Log Response: The response from the HTTP service is logged.
YAML
- route:
id: route-29bf
description: Query Param Demo
nodePrefixId: route-99f
from:
id: from-ce44
description: Start
uri: timer
parameters:
timerName: test
repeatCount: "1"
steps:
- setVariable:
id: setVariable-ec8d
description: "Set demo JSON "
name: json
expression:
constant:
id: constant-c086
expression: |-
{
"id": "12345",
"customer": {
"firstName": "Jane",
"lastName": "Doe"
}
}
- unmarshal:
id: unmarshal-a7df
description: Unmarshal to Object
variableSend: json
variableReceive: data
json:
id: json-a946
- setHeader:
id: setHeader-d181
description: Set Query Parameter
name: CamelHttpQuery
expression:
groovy:
id: groovy-8170
expression: "'name=' + variables.data.customer.firstName"
- to:
id: to-81a9
description: Call HTTP Service
variableReceive: response
uri: https
parameters:
httpMethod: GET
httpUri: https://api.agify.io
throwExceptionOnFailure: false
- log:
id: log-2181
description: Log result
message: ${variable.response}