How to handle events using Hypi’s Webhooks

After going through a series of posts on Hypi Directives, let’s check the creation of a webhook.

For demonstration purposes, we will use Printful Webhooks requests. Printful has a webhook simulator that sends the request to a webhook url.

A sample payload contains Package Shipment details in the form of Json. We will store these details in the following data type.

type PackageData {
    type: String
    created: DateTime
    retries: Int
    store: Int
    data: Json
}

Let’s create a graphql function (packageShipped) that processes the webhook request.

type Query {
  packageShipped(payload: WebhookPayload!): 
    WebhookResponse @tan(type:Groovy, inline: """ 
    import com.fasterxml.jackson.databind.ObjectMapper
    def mapper = new ObjectMapper()
    def package_data = mapper.readTree(payload.body)
    gql(\"""
    mutation {
        upsert(
            values: { 
                PackageData: [
                    { 
                        created: ${package_data.created}  
                        type: ${package_data.type}  
                        retries: ${package_data.retries} 
                        store: ${package_data.store} 
                        data: ${package_data.data} 
                        
                    }
                ] 
            }
        ) {
            id
        }
    }\"""
    )    
    return [
      "status": 200,
      "headers": payload.headers,
      "body" : payload.body
      ]
  """)
}
  • The signature of the function processing webhook request must be (payload: WebhookPayload): WebhookResponse
  • The payload data may be in json, xml or raw data
  • Using gql function, insert/save the values of the payload into the fields of PackageData type
  • Return the status as 200 and send back the body and header as it is.

Let’s create a Webhook object with the name ‘Package’ with the above query function packageShipped.

mutation Upsert($values: HypiUpsertInputUnion!) {
  upsert(values: $values) {
    id
  }
}
#input
{
  "values": {
    "Webhook": [
             {
                         
             "name": "Package",
            "query": {
            "type": "Query",
            "field": "packageShipped"
            }
          }
       ]
    }
}

Let’s say our domain is leisure.apps.hypi.app. So, our webhook url to send request to is
https://api.hypi.app/webhook/leisure.apps.hypi.app/Package

So our Hypi webhook is ready to receive the request!