1

I'm using the Java SDK to start a voice call using something similar to

Call.creator(to, from, callbackAddress)

I provide a URL (callbackAddress) that will receive the callback once the call is connected. Is there some way to configure this callback to be in JSON instead of "application/x-www-form-urlencoded; charset=UTF-8"?

The reason why I'm trying to do that is because I'm using Spring and ultimately I'm trying to receive the request parameters already in a deserialized Pojo in my RestController (parameter body in my example below), which is standard in SpringMVC. This is much easier to do using jackson, which requires a JSON request body

As a secondary question, is there a class in the Twilio SDK that encapsulates all the parameters in a request already or I would have to create such class?

Here is a dummy rest controller to illustrate what I'm trying to do. Note that the logic there with the "out of city" error is just a silly demo to show why I need to access the request parameters. All the samples I found about callbacks always ignored the request parameters and returned a static TwiML

@RestController
@RequestMapping(value = "/twilio", consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class TwilioCallbackController {
  @PostMapping
  public String handleCallback(RequestBody body /*this arg should have all request params*/) {
     log.info("received callback for callId {}", body.getCallSid()) 
     if (!body.toCity().equals("my-city")) {
        throw new Exception("outside of city");
     }
     return createTwiML(body);
  }
}
Hilikus
  • 9,954
  • 14
  • 65
  • 118

1 Answers1

2

Twilio developer evangelist here.

There is no way to have Twilio send you the webhook in JSON format, it will be sent as form encoded parameters. However, there shouldn't be an issue having Spring parse them.

As this answer suggests, you can create a class that will parse the parameters into it by creating a class with getters and setters for each of the parameters.

So, for example, you could create the following class:

public class TwilioWebhook {
  private String CallSid;
  private String From;

  public String getCallSid() {
    return CallSid;
  }

  public void setText(String CallSid) {
    this.CallSid = CallSid;
  }
}

Which you could then use to parse the CallSid from the incoming webhook parameters like:

@RestController
@RequestMapping(value = "/twilio", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public class TwilioCallbackController {
  @PostMapping
  public String handleCallback(TwilioWebhook request) {
     log.info("received callback for callId {}", request.getCallSid()) 
     // rest of the controller.
  }
}

You can parse all the parameters by adding to the TwilioWebhook class. You can see all the parameters that Twilio will send in the Twilio voice request documentation. There isn't a class in the Twilio SDK that does this for you though.

philnash
  • 70,667
  • 10
  • 60
  • 88