Access REST API and parse JSON response
REST API is the way how one application can get information from or make another application perform action by Internet communication.
In this sample, you will be shown how to make a REST API request to the service provided by Weather API for getting forecast and parse it. The sample will request a REST-service and than parse a response by the JsonSlurper class from the standard Groovy library.
Our goal is to get the current temperature, count of cloudy days, and the date of next rain.
<?xml version="1.0" encoding="UTF-8"?>
<config xmlns="http://web-harvest.sourceforge.net/schema/1.0/config" scriptlang="groovy">
<var-def name="api_response">
<http-extended url="https://api.openweathermap.org/data/2.5/weather" method="get">
<!-- Replace YOUR_APPID with your API key from OpenWeatherMap -->
<http-param-extended name="appid"><template>YOUR_APPID</template></http-param-extended>
<!-- Replace CITY_NAME with the desired city for which you want to retrieve weather information -->
<http-param-extended name="q"><template>CITY_NAME</template></http-param-extended>
<http-param-extended name="units"><template>metric</template></http-param-extended>
</http-extended>
</var-def>
<script><![CDATA[
import groovy.json.JsonSlurper
jsonSlurper = new JsonSlurper()
api_response = jsonSlurper.parseText(api_response.toString())
if (api_response != null && api_response.main != null) {
process_response(api_response)
} else {
error = "Service's provided null response. Please check service availability and your request."
sys.defineVariable("error", error)
log.error(error)
}
private void process_response(api_response) {
temperature = api_response.main.temp
sys.defineVariable("temperature", temperature)
weather = api_response.weather[0]
quantity_of_days = weather.description.findAll { it.contains('cloud') }.size()
sys.defineVariable("quantity_of_days", quantity_of_days)
next_rainy_day = weather.description.find { it.contains('rain') }
// if there isn't any rain soon export 'far away'
next_rainy_day = null == next_rainy_day ? 'far away' : next_rainy_day
sys.defineVariable("next_rainy_day", next_rainy_day)
}
]]></script>
<export include-original-data="false">
<case>
<if condition="${!sys.isVariableDefined('error')}">
<single-column name="Temperature" value="${temperature}"/>
<single-column name="Quantity of cloudy days" value="${quantity_of_days}"/>
<single-column name="Next rainy day" value="${next_rainy_day}"/>
</if>
<else>
<single-column name="Error description" value="${error}"/>
</else>
</case>
</export>
</config>