http
The HTTP extension allows scripts to make outbound HTTP requests to external APIs and services.
API
| Method | Description |
|---|---|
http.get(url, headers?) | GET request |
http.post(url, body?, headers?) | POST request |
http.put(url, body?, headers?) | PUT request |
http.delete(url, headers?) | DELETE request |
All methods return an object with:
| Property | Type | Description |
|---|---|---|
status | number | HTTP status code |
body | string | Response body |
headers | object | Response headers (lowercase keys) |
GET Request
const res = http.get("https://api.example.com/users");
if (res.status === 200) {
const users = JSON.parse(res.body);
print(JSON.stringify(users));
}
GET with Headers
const res = http.get("https://api.example.com/me", {
"Authorization": "Bearer " + token,
"Accept": "application/json"
});
POST Request
const res = http.post(
"https://api.example.com/users",
JSON.stringify({ name: "Alice", email: "alice@example.com" }),
{ "Content-Type": "application/json" }
);
if (res.status === 201) {
print("User created");
}
PUT Request
const res = http.put(
"https://api.example.com/users/1",
JSON.stringify({ name: "Alice Updated" }),
{ "Content-Type": "application/json" }
);
DELETE Request
const res = http.delete("https://api.example.com/users/1", {
"Authorization": "Bearer " + token
});
Error Handling
try {
const res = http.get("https://api.example.com/data");
if (res.status >= 400) {
response.setStatus(502);
print("Upstream error: " + res.status);
} else {
print(res.body);
}
} catch (e) {
response.setStatus(502);
print("Request failed: " + e.message);
}
Proxy Pattern
// Forward a request to an internal API
const res = http.get("http://internal-service:3000/data");
response.setHeader("Content-Type", res.headers["content-type"] || "application/json");
response.setStatus(res.status);
print(res.body);
Notes
- Requests have a 30-second timeout
- Redirects are followed automatically
- HTTPS is supported