How to configure an HTTP request using Hypi directive (@http)

We have seen @indices directive in the previous post. Now we will check @http directive to configure an HTTP request.

We will see two HTTP request configuration methods in separate posts. Now we will use the inline variable to define requestTemplate and responseTemplate. Please check more information on InlineHttpRequestTemplate here.

Let’s use the @http directive to send an HTTP request to the website https://countrylayer.com/ . A request to its APIs provides details of a country as a response.

Here is the sample schema.

type Mutation {
getCountryDetails(countryName: String, fullName: Boolean): Json @http(
    method: GET,
    url: "http://api.countrylayer.com/v2/name/$vars.countryName?access_key=$settings.APIKEY&fullText=$vars.fullName",
    headers: """{"Content-Type": "application/json"}"""
    inline: {
      requestTemplate: """{"name": "${vars.countryName}","fullText": "${vars.fullName}","access_key": "${settings.APIKEY}"}"""
      responseTemplate: """{"name": $!{response[0].name}, "alpha2code": $!{response[0].alpha2Code},"alpha3code": $!{response[0].alpha3Code},"continent": $!{response[0].region}}"""
    },
    saveAs: "Country"    
  )
}
  • The requestTemplate has the $vars.countryName and $vars.fullName variables that hold the input country name and fullName boolean value to be sent across. If the provided country name has been abbreviated, fullName is false otherwise it is true. (false for Sg and true for Singapore)
  • Notice the use of APIKEY environment variable. The value of this field has to be set at runtime and the same gets sent over in the HTTP request url.
  • The response has the form of a json array and the array has just one element (response[0]). responseTemplate extracts the name, alpha2code, alpha3code, region/continent information from the response .
  • The response gets saved in the Country object. Country is an in-built core data type of Hypi.

Let’s run the http request now by executing the getCountryDetails function.

#request
mutation {
  getCountryDetails(countryName:"India",fullName:true)
}
#response
{
  "data": {
    "getCountryDetails": {
      "name": "India",
      "alpha2code": "IN",
      "alpha3code": "IND",
      "continent": "Asia"
    }
  }
}

In the next post, we will see how to configure Http requests using requestTemplate object.