SQL Server
SQL Server
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 SQL Server Downloads
-- Important: See this note about string length limitations for strings returned by sp_OAMethod calls.
--
CREATE PROCEDURE ChilkatSample
AS
BEGIN
DECLARE @hr int
-- Important: Do not use nvarchar(max). See the warning about using nvarchar(max).
DECLARE @sTmp0 nvarchar(4000)
DECLARE @success int
SELECT @success = 0
-- 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}}}'
DECLARE @sbCurl int
EXEC @hr = sp_OACreate 'Chilkat.StringBuilder', @sbCurl OUT
IF @hr <> 0
BEGIN
PRINT 'Failed to create ActiveX component'
RETURN
END
EXEC sp_OAMethod @sbCurl, 'AppendLn', @success OUT, 'curl -X POST https://api.example.com/messages \'
EXEC sp_OAMethod @sbCurl, 'AppendLn', @success OUT, ' -H "Content-Type: application/json" \'
EXEC sp_OAMethod @sbCurl, 'AppendLn', @success OUT, ' -d ''{"text":"{{message}}"}'''
DECLARE @curl int
EXEC @hr = sp_OACreate 'Chilkat.HttpCurl', @curl OUT
-- In this example, the value we'll provide for the "message" variable
-- will contain chars that require JSON escaping.
EXEC sp_OAMethod @curl, 'SetVar', NULL, '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.
DECLARE @sbRawRequest int
EXEC @hr = sp_OACreate 'Chilkat.StringBuilder', @sbRawRequest OUT
EXEC sp_OAMethod @sbCurl, 'GetAsString', @sTmp0 OUT
EXEC sp_OAMethod @curl, 'ToRawRequest', @success OUT, @sTmp0, @sbRawRequest
IF @success = 0
BEGIN
EXEC sp_OAGetProperty @curl, 'LastErrorText', @sTmp0 OUT
PRINT @sTmp0
EXEC @hr = sp_OADestroy @sbCurl
EXEC @hr = sp_OADestroy @curl
EXEC @hr = sp_OADestroy @sbRawRequest
RETURN
END
EXEC sp_OAMethod @sbRawRequest, 'GetAsString', @sTmp0 OUT
PRINT @sTmp0
-- 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!\""}
EXEC @hr = sp_OADestroy @sbCurl
EXEC @hr = sp_OADestroy @curl
EXEC @hr = sp_OADestroy @sbRawRequest
END
GO