Skip to content

Instantly share code, notes, and snippets.

@theorigin
Last active January 9, 2024 12:10
Show Gist options
  • Save theorigin/fa3c58406ff7b4565ca2 to your computer and use it in GitHub Desktop.
Save theorigin/fa3c58406ff7b4565ca2 to your computer and use it in GitHub Desktop.
SQL Server code to POST to an API
DECLARE @Object AS INT;
DECLARE @ResponseText AS VARCHAR(8000);
DECLARE @Body AS VARCHAR(8000) =
'{
"what": 1,
"ever": "you",
"need": "to send as the body"
}'
EXEC sp_OACreate 'MSXML2.XMLHTTP', @Object OUT;
EXEC sp_OAMethod @Object, 'open', NULL, 'post','http://requestb.in/1h83e3n1', 'false'
EXEC sp_OAMethod @Object, 'setRequestHeader', null, 'Content-Type', 'application/json'
EXEC sp_OAMethod @Object, 'send', null, @body
EXEC sp_OAMethod @Object, 'responseText', @ResponseText OUTPUT
SELECT @ResponseText
EXEC sp_OADestroy @Object
@Aviramyo3
Copy link

Thanks, dude.
I used it to send a request to Rabbit.
I didn't find any article on how to send the @Body part.
Well done.

@ecdbert
Copy link

ecdbert commented Oct 27, 2020

Beautiful. Looked everywhere for a code that's working (POST and Body parameters).

@jozimarso
Copy link

Hi,

I need to send post with authentication bearer token, how to do?

Thanks.

@bilobi
Copy link

bilobi commented Sep 16, 2022

Hi,
The solution to your question is in the example below.

`DECLARE @object AS INT;
DECLARE @responseText AS VARCHAR(8000);
DECLARE @Body AS varchar(250) =
'{
"username": "bilobi",
"password": "72749764"
}'

EXEC sp_OACreate 'MSXML2.XMLHTTP', @object OUT;
EXEC sp_OAMethod @object, 'open', NULL, 'post','http://localhost/api/authenticate', 'false'

EXEC sp_OAMethod @object, 'setRequestHeader', null, 'Content-Type', 'application/json'
EXEC sp_OAMethod @object, 'send', null, @Body

EXEC sp_OAMethod @object, 'responseText', @responseText OUTPUT

SELECT JSON_VALUE(@responseText,'$.token')

EXEC sp_OADestroy @Object`

@sbertolinconsejo
Copy link

Hi there, does anyone know how to send a body largen than varchar(max)? Is it possible using only SQL server?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment