DataFlex
DataFlex
curl with Variable Substitution in the Request Body
See more CURL Examples
This example demonstrates using variables located in the request body with the {{variable_name}} syntax.Chilkat DataFlex Downloads
Use ChilkatAx-win32.pkg
Procedure Test
Boolean iSuccess
Handle hoSbCurl
Handle hoCurl
Variant vSbRawRequest
Handle hoSbRawRequest
String sTemp1
Move False To iSuccess
// Variables can also be used within the HTTP request body.
// Variable names are enclosed between {{ and }}
// Here is a curl command with two variables {{name}} and {{age}} located in the data.
// curl -X POST https://api.example.com/data \
// -H "Content-Type: application/json" \
// -d '{"name":"{{name}}","age":{{age}}}'
Get Create (RefClass(cComChilkatStringBuilder)) To hoSbCurl
If (Not(IsComObjectCreated(hoSbCurl))) Begin
Send CreateComObject of hoSbCurl
End
Get ComAppendLn Of hoSbCurl "curl -X POST https://api.example.com/data \" To iSuccess
Get ComAppendLn Of hoSbCurl ' -H "Content-Type: application/json" \' To iSuccess
Get ComAppendLn Of hoSbCurl ' -d '{"name":"{{name}}","age":{{age}}}'' To iSuccess
Get Create (RefClass(cComChilkatHttpCurl)) To hoCurl
If (Not(IsComObjectCreated(hoCurl))) Begin
Send CreateComObject of hoCurl
End
// Provide values for variables.
Send ComSetVar To hoCurl "name" "Alice"
Send ComSetVar To hoCurl "age" "30"
// To demonstrate how the variables are replaced, this example does not execute the curl command.
// Instead, it generates the raw HTTP request that would be sent if the curl command were run.
Get Create (RefClass(cComChilkatStringBuilder)) To hoSbRawRequest
If (Not(IsComObjectCreated(hoSbRawRequest))) Begin
Send CreateComObject of hoSbRawRequest
End
Get ComGetAsString Of hoSbCurl To sTemp1
Get pvComObject of hoSbRawRequest to vSbRawRequest
Get ComToRawRequest Of hoCurl sTemp1 vSbRawRequest To iSuccess
If (iSuccess = False) Begin
Get ComLastErrorText Of hoCurl To sTemp1
Showln sTemp1
Procedure_Return
End
Get ComGetAsString Of hoSbRawRequest To sTemp1
Showln sTemp1
// Output:
// POST /data HTTP/1.1
// Host: api.example.com
// Content-Type: application/json
// Content-Length: 25
//
// {"name":"Alice","age":30}
// --------------------------------------------------------------------------------------------------
// Note: Variable substitution in the request body can be turned off by
// setting the EnableBodyVars property equal to False
Set ComEnableBodyVars Of hoCurl To False
Get ComGetAsString Of hoSbCurl To sTemp1
Get pvComObject of hoSbRawRequest to vSbRawRequest
Get ComToRawRequest Of hoCurl sTemp1 vSbRawRequest To iSuccess
If (iSuccess = False) Begin
Get ComLastErrorText Of hoCurl To sTemp1
Showln sTemp1
Procedure_Return
End
Get ComGetAsString Of hoSbRawRequest To sTemp1
Showln sTemp1
// The raw request with body variable substitution disable:
// Host: api.example.com
// Content-Type: application/json
// Content-Length: 33
//
// {"name":"{{name}}","age":{{age}}}
End_Procedure