Lesson 3 of 4 Retrieval-Augmented Generation in SQL

Calling a Language Model with sp_invoke_external_rest_endpoint

This lesson explains how to build a chat request, call the model endpoint and handle the result codes.

Learning outcomes

After completing this lesson, you will be able to:

  • Describe the structure of a chat completions request.
  • Explain the parameters and permissions of sp_invoke_external_rest_endpoint.
  • Identify how to handle HTTP error codes.

Building the request

A chat completions request has a messages array. The system message carries the instructions: answer only from the provided data, cite product IDs, say when the data does not contain the answer, and keep a defined tone and length. The user message carries the question and the retrieved JSON. Settings such as max_completion_tokens limit the answer length, and response_format with a JSON schema requests structured output. The body is built with JSON_OBJECT and JSON_ARRAY so that the question and data are escaped correctly; concatenating user text into a JSON string breaks on quotes and can let a user inject extra JSON.

DECLARE @system nvarchar(max) = N'You are a product advisor. Answer only from the products in the JSON data. '
                              + N'Cite product ids in square brackets. If no product fits, say so.';
DECLARE @user   nvarchar(max) = CONCAT(N'Question: ', @question, NCHAR(10), N'Products: ', @context);

DECLARE @payload nvarchar(max) = JSON_OBJECT(
    'model': 'gpt-5.4-mini',
    'messages': JSON_ARRAY(
        JSON_OBJECT('role': 'system', 'content': @system),
        JSON_OBJECT('role': 'user',   'content': @user)),
    'max_completion_tokens': 600);
Spot the bug

A fragile request body

Exam skills 3.3.2

Find the line that breaks when a user's question contains a quote.

Log in to try this activity Interactive activities are free with an account.

Calling the endpoint

sp_invoke_external_rest_endpoint sends the request. Its parameters are the URL, the method (POST by default), optional headers as flat JSON, the payload, a database scoped credential, a timeout in seconds (default 30, maximum 230), a retry count (0 to 10, for 408, 429 and 5xx responses) and an OUTPUT parameter for the response.

DECLARE @ret int, @response nvarchar(max);
EXEC @ret = sp_invoke_external_rest_endpoint
     @url        = N'https://contoso-ai.openai.azure.com/openai/v1/chat/completions',
     @method     = 'POST',
     @payload    = @payload,
     @credential = [https://contoso-ai.openai.azure.com],
     @timeout    = 120,
     @retry_count = 3,
     @response   = @response OUTPUT;

The caller needs EXECUTE ANY EXTERNAL ENDPOINT and REFERENCES on the credential, and the credential uses the server's managed identity with the Cognitive Services OpenAI User role. In Azure SQL Database and Managed Instance the URL must be in an allow-listed domain, such as *.openai.azure.com; the procedure is enabled by default in Azure SQL Database and SQL database in Fabric and needs external rest endpoint enabled in SQL Server 2025.

Match the pairs

sp_invoke_external_rest_endpoint

Exam skills 3.3.4

Match each parameter with its purpose.

Log in to try this activity Interactive activities are free with an account.

Handling the result

The procedure returns 0 when the HTTP status is 2xx; otherwise it returns the status code, and connection failures raise an exception. The handling of common outcomes is summarized in the following table.

OutcomeMeaningHandling
0 (2xx)SuccessExtract the answer
400Bad request, such as an invalid body or a prompt over the context limitFix the payload or reduce retrieved data
401 or 403Authentication or authorization failureCheck the managed identity, role assignment and credential name
429Throttled by the deployment's quotaRetry with backoff (@retry_count) or raise the quota
5xx or timeoutService problem or slow responseRetry; raise @timeout for long answers

Outbound calls hold an HTTP_EXTERNAL_CONNECTION wait and count against the database's limit on concurrent outbound connections, so long-running model calls should not run inside transactions that hold locks.

Match the pairs

Outcomes of a model call

Exam skills 3.3.4

Match each outcome with how to handle it.

Log in to try this activity Interactive activities are free with an account.
Worked example

A 401 response

A RAG procedure that worked with an API key credential now returns 401 after the team switched to a credential with IDENTITY = 'Managed Identity'. The logical server's system-assigned identity is enabled. What is the most likely missing step?

The server's managed identity needs a role on the Azure OpenAI or Foundry resource, typically Cognitive Services OpenAI User, and the credential's SECRET must specify the resource ID https://cognitiveservices.azure.com. Without the role, the token is valid but not authorized. Raising the timeout or retry count does not fix authentication, and EXECUTE ANY EXTERNAL ENDPOINT governs whether the procedure can be called at all, which it evidently can.

Check yourself

What does sp_invoke_external_rest_endpoint return when the HTTP status is 429?

Show answer

429, the HTTP status code; it returns 0 only for 2xx responses.

Exam Tips

Remember for the exam

  • Build the body with JSON_OBJECT and JSON_ARRAY; never concatenate raw text into JSON.
  • Return value 0 means 2xx; otherwise it is the HTTP status code.
  • Default timeout 30 seconds (max 230); retry_count retries 408, 429 and 5xx.
  • Requires EXECUTE ANY EXTERNAL ENDPOINT and an allow-listed URL in Azure SQL.