BASH

Perform Authenticated API Request with curl

Discover how to use `curl` in Bash to make authenticated POST requests to web APIs, including sending JSON payloads and authentication headers.

#!/bin/bash

API_ENDPOINT="https://api.example.com/data"
AUTH_TOKEN="your_jwt_or_api_key"

JSON_PAYLOAD='{
  "name": "New Item",
  "value": 123
}'

RESPONSE=$(curl -s -X POST \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $AUTH_TOKEN" \
  -d "$JSON_PAYLOAD" \
  "$API_ENDPOINT")

if [ $? -eq 0 ]; then
  echo "API Request Successful:"
  echo "$RESPONSE" | python -m json.tool # Pretty print JSON using Python
else
  echo "API Request Failed."
  echo "$RESPONSE"
fi
How it works: This script demonstrates how to send an authenticated POST request to an API endpoint using `curl`. It sets the `Content-Type` header to `application/json`, includes an `Authorization` header with a bearer token, and sends a JSON payload. The response is captured and then pretty-printed using Python's `json.tool` module, which is helpful for readability. This is frequently used for scripting interactions with RESTful APIs.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs