Enhancing SQL Server with External API Calls: A Guide to sp_invoke_external_rest_endpoint

In the bustling world of database management, SQL Server shines as a beacon of strength, flexibility, and a treasure trove of features ready to tackle a wide array of data challenges. Among its many jewels is a feature that feels almost like magic: the ability to chat with external APIs right from the cozy confines of T-SQL code, courtesy of the sp_invoke_external_rest_endpoint stored procedure. This little trick opens doors to a whole new universe of possibilities, from pulling in fresh data on the fly to tapping into the vast resources of the internet to pump up your database’s muscles in real time. Today, let’s dive into some of the coolest ways to wield sp_invoke_external_rest_endpoint to call upon external APIs from within the heart of SQL Server, complete with hands-on T-SQL spells.

When You Want to Know More About Your Customers

Picture this: you’re the guardian of a customer database, and you’re itching to add some spice to those records. Maybe you want to pin down where your customers are hanging out based on their IP addresses or snag some extra contact details. With sp_invoke_external_rest_endpoint, you can summon an external geolocation API or a contact enrichment service to fetch this info on the spot and give your database a makeover.

Here’s How You Do It:

DECLARE @Response NVARCHAR(MAX)
EXEC sp_invoke_external_rest_endpoint
    @http_method = N'GET',
    @endpoint_uri = N'https://api.ipgeolocation.io/ipgeo?apiKey=[Your_API_Key]&ip=[Customer_IP]',
    @response_content = @Response OUTPUT

-- Now, let's sift through that JSON response and find our treasure
-- Assuming we got back latitude and longitude
DECLARE @Latitude NVARCHAR(50), @Longitude NVARCHAR(50)
SELECT @Latitude = JSON_VALUE(@Response, '$.latitude'), 
       @Longitude = JSON_VALUE(@Response, '$.longitude')

-- Time to update those records with our newfound knowledge

Making Transactions Smooth Like Butter

If you’re in the game of handling transactions and payments, why not make SQL Server your one-stop shop for everything payment-related? Using sp_invoke_external_rest_endpoint, you can kick off payments, peek at payment statuses, or even handle refunds without ever stepping out of your database.

Let’s See It in Action:

DECLARE @PaymentDetails NVARCHAR(MAX), @Response NVARCHAR(MAX)
SET @PaymentDetails = '{ "amount": 100, "currency": "USD", "source": "card_1A2b3C4d", "description": "Invoice Payment" }'

EXEC sp_invoke_external_rest_endpoint
    @http_method = N'POST',
    @endpoint_uri = N'https://api.paymentgateway.com/v1/payments',
    @request_content = @PaymentDetails,
    @response_content = @Response OUTPUT

-- Now, let's decode that payment response and log it
-- Assuming we get back a status
INSERT INTO PaymentLogs (PaymentStatus, Response)
SELECT JSON_VALUE(@Response, '$.status'), @Response

Keeping Your Data Safe in the Cloud

Backing up your precious data to the cloud is like keeping your treasures in a vault. With sp_invoke_external_rest_endpoint, SQL Server can chat directly with cloud storage services like AWS S3, Azure Blob Storage, or Google Cloud Storage to stash your backups safely away.

Example Time:

DECLARE @BackupFile NVARCHAR(MAX), @Response NVARCHAR(MAX)
SET @BackupFile = 'path/to/your/backupfile.bak'

EXEC sp_invoke_external_rest_endpoint
    @http_method = N'PUT',
    @endpoint_uri = N'https://yourstorageaccount.blob.core.windows.net/backups/backupfile.bak?sp=racwdl&st=2021-09-01T22:37:00Z&se=2021-09-30T22:37:00Z&spr=https&sv=2020-08-04&sr=b&sig=[Your_SAS_Token]',
    @request_content = @BackupFile,
    @response_content = @Response OUTPUT

-- Let's make sure our backup landed safely

Bringing the World Into Your Reports

When it’s time to whip up some reports, why not sprinkle in some data from the outside world? Whether you’re after the pulse of the financial markets, the latest weather forecast, or any other kind of external intel, sp_invoke_external_rest_endpoint is your gateway to real-time data infusion.

Here’s a Peek:

DECLARE @Response NVARCHAR(MAX)
EXEC sp_invoke_external_rest_endpoint
    @http_method = N'GET',
    @endpoint_uri = N'https://api.weatherapi.com/v1/current.json?key=[Your_API_Key]&q=New York',
    @response_content = @Response OUTPUT

-- Time to fold that external data into your report
-- Let's say we're looking at temperature
SELECT JSON_VALUE(@Response, '$.current.temp_c') AS CurrentTemperature

Wrapping Up

Unlocking the power of sp_invoke_external_rest_endpoint in SQL Server is like finding a secret passage that leads to a treasure trove of capabilities for your database adventures. From enriching data on the fly to integrating with external services, automating backups, or jazzing up your reports with live data, the realms to explore are endless. Armed with these practical examples, you’re all set to elevate your SQL Server projects to legendary status.

Related Posts

Troubleshooting Missing SQL Server Statistics

Learn how to diagnose and fix missing SQL Server statistics through a practical troubleshooting guide, including step-by-step solutions and best practices.

Read more

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Discover more from The DBA Hub

Subscribe now to keep reading and get access to the full archive.

Continue reading