How to Pass X-API-Key Header in API Requests (2026)
A practical guide to API key authentication via headers
Start Building with Hypereal
Access Kling, Flux, Sora, Veo & more through a single API. Free credits to start, scale to millions.
No credit card required • 100k+ developers • Enterprise ready
How to Pass X-API-Key Header in API Requests (2026)
The X-API-Key header is one of the most common authentication methods for REST APIs. It is simple, widely supported, and easy to implement across any programming language. This guide shows you exactly how to pass the X-API-Key header in every major language and tool, along with security best practices.
What Is the X-API-Key Header?
The X-API-Key header is a custom HTTP header used to send an API key with your request. The API server checks this key to authenticate and authorize the caller.
A typical request looks like this:
GET /api/v1/users HTTP/1.1
Host: api.example.com
X-API-Key: sk_live_abc123def456
Content-Type: application/json
The X- prefix historically indicated a non-standard header, though this convention has been deprecated by RFC 6648. Despite that, X-API-Key remains the most widely used name for API key headers.
X-API-Key vs Other Authentication Methods
| Method | Header | Use Case | Security Level |
|---|---|---|---|
| X-API-Key | X-API-Key: <key> |
Service-to-service, public APIs | Medium |
| Bearer Token | Authorization: Bearer <token> |
User authentication, OAuth | High |
| Basic Auth | Authorization: Basic <base64> |
Simple username/password | Low |
| Query Parameter | ?api_key=<key> |
Legacy APIs (avoid this) | Low |
How to Pass X-API-Key in cURL
cURL is the quickest way to test API key authentication from the command line:
# GET request with X-API-Key
curl -H "X-API-Key: sk_live_abc123def456" \
https://api.example.com/v1/users
# POST request with X-API-Key and JSON body
curl -X POST \
-H "X-API-Key: sk_live_abc123def456" \
-H "Content-Type: application/json" \
-d '{"name": "John", "email": "john@example.com"}' \
https://api.example.com/v1/users
# Using an environment variable (recommended)
export API_KEY="sk_live_abc123def456"
curl -H "X-API-Key: $API_KEY" \
https://api.example.com/v1/users
How to Pass X-API-Key in Python
Using the `requests` Library
import os
import requests
api_key = os.environ["API_KEY"]
# GET request
response = requests.get(
"https://api.example.com/v1/users",
headers={"X-API-Key": api_key}
)
print(response.json())
# POST request
response = requests.post(
"https://api.example.com/v1/users",
headers={"X-API-Key": api_key},
json={"name": "John", "email": "john@example.com"}
)
print(response.status_code)
Using a Session for Multiple Requests
If you make multiple requests to the same API, use a session to avoid repeating headers:
import os
import requests
session = requests.Session()
session.headers.update({
"X-API-Key": os.environ["API_KEY"],
"Content-Type": "application/json"
})
# All requests in this session include the API key
users = session.get("https://api.example.com/v1/users").json()
posts = session.get("https://api.example.com/v1/posts").json()
Using `httpx` (Async)
import os
import httpx
async def fetch_users():
async with httpx.AsyncClient(
headers={"X-API-Key": os.environ["API_KEY"]}
) as client:
response = await client.get("https://api.example.com/v1/users")
return response.json()
How to Pass X-API-Key in JavaScript
Using Fetch API (Browser & Node.js)
const apiKey = process.env.API_KEY;
// GET request
const response = await fetch("https://api.example.com/v1/users", {
headers: {
"X-API-Key": apiKey,
},
});
const data = await response.json();
// POST request
const postResponse = await fetch("https://api.example.com/v1/users", {
method: "POST",
headers: {
"X-API-Key": apiKey,
"Content-Type": "application/json",
},
body: JSON.stringify({
name: "John",
email: "john@example.com",
}),
});
Using Axios
import axios from "axios";
// Create an axios instance with default headers
const api = axios.create({
baseURL: "https://api.example.com/v1",
headers: {
"X-API-Key": process.env.API_KEY,
},
});
// All requests include the API key automatically
const users = await api.get("/users");
const newUser = await api.post("/users", {
name: "John",
email: "john@example.com",
});
How to Pass X-API-Key in Go
package main
import (
"fmt"
"net/http"
"os"
"io"
)
func main() {
apiKey := os.Getenv("API_KEY")
req, err := http.NewRequest("GET", "https://api.example.com/v1/users", nil)
if err != nil {
panic(err)
}
req.Header.Set("X-API-Key", apiKey)
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
fmt.Println(string(body))
}
How to Pass X-API-Key in PHP
<?php
$apiKey = getenv('API_KEY');
// Using cURL
$ch = curl_init('https://api.example.com/v1/users');
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => [
"X-API-Key: $apiKey",
"Content-Type: application/json",
],
]);
$response = curl_exec($ch);
$data = json_decode($response, true);
curl_close($ch);
// Using Guzzle
$client = new \GuzzleHttp\Client([
'base_uri' => 'https://api.example.com/v1/',
'headers' => [
'X-API-Key' => $apiKey,
],
]);
$response = $client->get('users');
$data = json_decode($response->getBody(), true);
How to Pass X-API-Key in API Testing Tools
Postman
- Open your request in Postman
- Click the Headers tab
- Add a new header:
- Key:
X-API-Key - Value:
{{api_key}}(use a Postman variable)
- Key:
- Set the variable in your Postman environment for reuse
HTTPie
# HTTPie uses a clean header syntax
http GET https://api.example.com/v1/users \
X-API-Key:sk_live_abc123def456
# POST with JSON body
http POST https://api.example.com/v1/users \
X-API-Key:sk_live_abc123def456 \
name=John email=john@example.com
Security Best Practices
1. Never Hardcode API Keys
# BAD - key is in source code
headers = {"X-API-Key": "sk_live_abc123def456"}
# GOOD - key comes from environment variable
headers = {"X-API-Key": os.environ["API_KEY"]}
2. Use Environment Variables or Secret Managers
# .env file (never commit this)
API_KEY=sk_live_abc123def456
# Load with dotenv in your application
Add .env to your .gitignore:
# .gitignore
.env
.env.local
.env.production
3. Always Use HTTPS
API keys sent over HTTP are visible in plaintext. Always use HTTPS endpoints:
# BAD - key visible to anyone on the network
curl -H "X-API-Key: sk_live_abc123" http://api.example.com/v1/users
# GOOD - encrypted with TLS
curl -H "X-API-Key: sk_live_abc123" https://api.example.com/v1/users
4. Rotate Keys Regularly
Most API providers let you create multiple keys. Use separate keys for development and production, and rotate them periodically.
5. Restrict Key Permissions
If your API provider supports it, scope keys to specific operations:
| Key | Permissions | Environment |
|---|---|---|
sk_dev_xxx |
Read only | Development |
sk_staging_xxx |
Read/Write | Staging |
sk_prod_xxx |
Read/Write (restricted IPs) | Production |
Handling Errors
Common HTTP responses when API key authentication fails:
| Status Code | Meaning | Likely Cause |
|---|---|---|
| 401 Unauthorized | Missing or invalid key | Typo in key, expired key |
| 403 Forbidden | Valid key, insufficient permissions | Key lacks required scope |
| 429 Too Many Requests | Rate limit exceeded | Too many requests per minute |
response = requests.get(url, headers={"X-API-Key": api_key})
if response.status_code == 401:
print("Invalid API key. Check your credentials.")
elif response.status_code == 403:
print("Your API key doesn't have permission for this endpoint.")
elif response.status_code == 429:
retry_after = response.headers.get("Retry-After", 60)
print(f"Rate limited. Retry after {retry_after} seconds.")
Conclusion
Passing the X-API-Key header is straightforward in any language or tool. The key takeaway is to never hardcode your API keys, always use HTTPS, and store keys in environment variables or secret managers.
If you are looking for a media generation API that uses X-API-Key authentication, Hypereal AI provides simple API key-based access to AI image generation, video creation, and more -- all following the patterns shown in this guide.
Related Articles
Start Building Today
Get 35 free credits on signup. No credit card required. Generate your first image in under 5 minutes.
