Sample code for 30+ languages & platforms
DataFlex

curl with Variable Substitution in a JSON Request Body

See more CURL Examples

This example shows how to use variables inside a JSON request body using the {{variable_name}} syntax. When the HTTP request’s Content-Type indicates JSON, Chilkat automatically applies proper JSON escaping to each substituted value, ensuring the resulting JSON remains valid.

Chilkat DataFlex Downloads

DataFlex
Use ChilkatAx-win32.pkg

Procedure Test
    Boolean iSuccess
    Handle hoSbCurl
    Handle hoCurl
    Variant vSbRawRequest
    Handle hoSbRawRequest
    String sTemp1

    Move False To iSuccess

    // Variable names are enclosed between {{ and }}
    // Important: The variable {{var_name}} should be placed inside the quotes.

    // This is correct:
    // curl -X POST https://api.example.com/messages \
    //   -H "Content-Type: application/json" \
    //   -d '{"text":"{{message}}"}'

    // This is incorrect:
    //   -d '{"text":{{message}}}'

    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/messages \" To iSuccess
    Get ComAppendLn Of hoSbCurl '  -H "Content-Type: application/json" \' To iSuccess
    Get ComAppendLn Of hoSbCurl '  -d '{"text":"{{message}}"}'' To iSuccess

    Get Create (RefClass(cComChilkatHttpCurl)) To hoCurl
    If (Not(IsComObjectCreated(hoCurl))) Begin
        Send CreateComObject of hoCurl
    End

    // In this example, the value we'll provide for the "message" variable
    // will contain chars that require JSON escaping.
    Send ComSetVar To hoCurl "message" 'He said "Hello, world!"'

    // 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

    // The output is shown below.
    // Notice that the quote chars around "Hello World!" are properly JSON escaped.

    // POST /messages HTTP/1.1
    // Host: api.example.com
    // Content-Type: application/json
    // Content-Length: 36
    // 
    // {"text":"He said \"Hello, world!\""}


End_Procedure