Skip to main content

How to Interact with a REST API from a Batch Script

Modern IT environments rely heavily on REST APIs to communicate with web services, cloud platforms, and third-party applications. While pure Batch scripting does not have a native "HTTP Request" command, modern Windows 10 and 11 environments include powerful built-in tools like curl.exe and PowerShell's Invoke-RestMethod.

In this guide, we will demonstrate how to send GET and POST requests to a REST API directly from a Batch script using these native tools.

Method 1: Using the Native curl Command

Starting with Windows 10 version 1803, curl.exe is included as a native system tool. It is the most robust and widely recognized command-line HTTP client.

curl vs. curl.exe

In cmd.exe, typing curl invokes curl.exe directly. However, in PowerShell, curl is an alias for Invoke-WebRequest. When calling curl from within a PowerShell context or mixed scripts, always use the full name curl.exe to ensure you invoke the correct tool.

Making a GET Request

To retrieve data from an API (e.g., getting a fake JSON response):

@echo off
setlocal

set "apiUrl=https://jsonplaceholder.typicode.com/todos/1"

echo Fetching data from: %apiUrl%
echo.

:: Use curl.exe to fetch the JSON response
:: -s = silent (no progress bar), -f = fail silently on HTTP errors
curl.exe -s -f "%apiUrl%"

if %errorlevel% NEQ 0 (
echo.
echo [ERROR] Request failed with error code: %errorlevel%
)

echo.
pause

Making a POST Request with Headers

To send JSON data to an API, you must specify the HTTP Method (-X POST), provide the Headers (-H), and include the Data payload (-d).

@echo off
setlocal

set "apiUrl=https://jsonplaceholder.typicode.com/posts"

:: Define JSON payload in a file to avoid escaping issues
(
echo {
echo "title": "Batch Test",
echo "body": "This is a test from CMD",
echo "userId": 1
echo }
) > "%TEMP%\payload.json"

echo Sending POST request to %apiUrl%...
echo.

:: Send request using payload file (@) instead of inline string
curl.exe -s -f -X POST "%apiUrl%" -H "Content-Type: application/json" -d @"%TEMP%\payload.json"

if %errorlevel% NEQ 0 (
echo.
echo [ERROR] Request failed with error code: %errorlevel%
)

:: Clean up temp file
del "%TEMP%\payload.json" 2>nul

echo.
pause
Why Use a Payload File?

Embedding JSON directly in a Batch variable requires escaping every double quote with a backslash for curl (\"), and Batch itself uses " for argument delimiting. This double-escaping is fragile and breaks easily with complex payloads. Writing the JSON to a temporary file and using curl's -d @filename syntax avoids all escaping issues entirely.

Capturing the Response into a Variable

To use the API response in subsequent Batch logic, redirect curl's output to a temporary file and read it back:

@echo off
setlocal enabledelayedexpansion

set "apiUrl=https://jsonplaceholder.typicode.com/todos/1"
set "tempFile=%TEMP%\api_response.json"

:: Fetch and save response
curl.exe -s -f "%apiUrl%" -o "%tempFile%"

if %errorlevel% NEQ 0 (
echo [ERROR] Request failed.
pause
exit /b
)

:: Read each line of the response
echo Response:
for /f "usebackq delims=" %%A in ("%tempFile%") do (
echo %%A
)

:: Clean up
del "%tempFile%" 2>nul
pause
Parsing JSON in Batch

Batch has no native JSON parser. For simple responses, you can use findstr to extract a specific value by pattern. For complex JSON, use the PowerShell bridge (Method 2) which automatically deserializes JSON into objects with named properties.

Method 2: Using the PowerShell Bridge

If curl.exe is not available, or if you need to perform complex JSON parsing after receiving the response, bridging to PowerShell is highly effective. PowerShell's Invoke-RestMethod automatically parses JSON into usable objects.

Fetching and Parsing JSON with PowerShell

@echo off
setlocal

set "apiUrl=https://jsonplaceholder.typicode.com/users/1"

echo Querying API via PowerShell...

:: Fetch data and extract just the 'name' property
for /f "usebackq delims=" %%A in (`
powershell -NoProfile -Command "(Invoke-RestMethod -Uri '%apiUrl%').name"
`) do set "userName=%%A"

if not defined userName (
echo [ERROR] Failed to retrieve user name.
pause
exit /b
)

echo.
echo User Name Retrieved: %userName%
pause

Sending a POST Request with PowerShell

@echo off
setlocal

set "apiUrl=https://jsonplaceholder.typicode.com/posts"

for /f "usebackq delims=" %%A in (`
powershell -NoProfile -Command ^
"$body = @{title='Batch Test'; body='Test from CMD'; userId=1} | ConvertTo-Json; " ^
"(Invoke-RestMethod -Uri '%apiUrl%' -Method Post -ContentType 'application/json' -Body $body).id"
`) do set "newId=%%A"

echo Created post with ID: %newId%
pause
Why PowerShell for POST Requests?

PowerShell's Invoke-RestMethod handles JSON serialization, character encoding, and HTTP headers automatically. Building the payload as a PowerShell hashtable (@{...}) and piping it through ConvertTo-Json avoids all the quote-escaping challenges that make inline JSON in Batch so fragile.

Why Interact with REST APIs in Batch?

  1. Cloud Integration: Triggering a CI/CD pipeline build, sending a message to a Slack/Discord webhook, or creating a JIRA ticket.
  2. System Monitoring: Pulling the current status of a web service before proceeding with a local maintenance script.
  3. Data Ingestion: Downloading the latest configuration file or threat-intelligence list from a remote server before a scan.

Important Considerations

Authentication

For APIs requiring authentication, use the -H "Authorization: Bearer YOUR_TOKEN" header with curl.exe. Never hardcode tokens directly in scripts stored in shared locations. Instead, read tokens from environment variables or a secured file:

set /p "token=" < "%USERPROFILE%\.api_token"
curl.exe -s -f -H "Authorization: Bearer %token%" "%apiUrl%"
Proxy Servers

If your corporate environment uses a proxy, you may need to configure curl.exe using the -x or --proxy flag:

curl.exe -s -x "http://proxy.corp.local:8080" "%apiUrl%"

PowerShell's Invoke-RestMethod respects the system proxy settings by default but can be overridden with the -Proxy parameter.

Conclusion

Interacting with REST APIs transforms your Batch scripts from isolated local tasks into powerful, connected automation tools. Whether you use the robust, industry-standard curl.exe or leverage the parsing power of the PowerShell bridge, you can integrate your local Windows environment with virtually any modern web service, cloud platform, or notification system.