Documentation

Guides

Using the API Directly

Making direct HTTP requests to the A4F API without relying on specific SDKs.

Introduction

While using SDKs like the OpenAI SDK (see our OpenAI SDK guide) can simplify interactions, you can also make direct HTTP requests to the A4F API. This approach offers maximum flexibility and can be useful in environments where SDKs are not available or when you need fine-grained control over the request.

This guide covers the essentials for making direct API calls to A4F, focusing on the chat completions endpoint.

Endpoint URL

The primary A4F endpoint for chat completions is:

POST https://api.a4f.co/v1/chat/completions

Other potential endpoints (e.g., for model listing, image generation) will follow a similar base URL structure (https://api.a4f.co/v1/...). Refer to the API Reference for specific endpoint paths.

Authentication

All direct API requests must be authenticated using your A4F API key. The key should be included in the `Authorization` header as a Bearer token.

Authorization: Bearer YOUR_A4F_API_KEY

Obtain your API key from the A4F Dashboard. More details can be found in the Authentication documentation.

Request Body (Chat Completions)

For the /v1/chat/completions endpoint, the request body must be a JSON object adhering to the OpenAI API specification. Key fields include:

  • model: (String, required) The A4F provider-prefixed model ID (e.g., "provider-1/chatgpt-4o-latest").
  • messages: (Array of objects, required) The conversation history. Each message object should have role and content.
  • Other optional parameters like temperature, max_tokens, stream, tools, etc.

For a comprehensive list of parameters, see the Parameters documentation and the Chat Completion API reference.

Headers

In addition to `Authorization`, ensure you set the `Content-Type` header correctly for POST requests:

Content-Type: application/json

For information on A4F-specific conceptual headers, refer to the Setting Headers guide.

Example Requests

Python (using `requests` library)

import requests
import json
import os
A4F_CHAT_COMPLETIONS_URL = "https://api.a4f.co/v1/chat/completions"
headers = {
"Authorization": A4F_API_KEY",
"Content-Type": "application/json",
}
payload = {
"model": "provider-1/chatgpt-4o-latest",
"messages": [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "What is the weather like in Paris?"}
],
"temperature": 0.7,
"max_tokens": 100
}
try:
response = requests.post(A4F_CHAT_COMPLETIONS_URL, headers=headers, json=payload, timeout=60)
response.raise_for_status()
data = response.json()
print("Successful Response:")
# print(json.dumps(data, indent=2))
if data.get("choices") and len(data["choices"]) > 0:
print("Assistant:", data["choices"][0].get("message", {}).get("content"))
else:
print("No choices found in response:", data)
except requests.exceptions.Timeout:
print("Request timed out.")
except requests.exceptions.HTTPError as http_err:
print(f"HTTP error occurred: {http_err}")
print(f"Response content: {response.text}")
except requests.exceptions.RequestException as req_err:
print(f"Other request error occurred: {req_err}")
except json.JSONDecodeError:
print("Failed to decode JSON response.")
print(f"Raw response content: {response.text}")
except Exception as e:
print(f"An unexpected error occurred: {e}")

Node.js (using native `fetch`)

async function callA4FDirectly() {
const A4F_API_KEY: string = process.env.A4F_API_KEY || "YOUR_A4F_API_KEY";
const A4F_CHAT_COMPLETIONS_URL: string = "https://api.a4f.co/v1/chat/completions";
const headers: HeadersInit = {
"Authorization": `Bearer ${A4F_API_KEY}`,
"Content-Type": "application/json",
};
const body = JSON.stringify({
model: "provider-3/claude-3-haiku-20240307", // Specify A4F provider-prefixed model ID
messages: [
{ role: "system", content: "You are an expert historian." },
{ role: "user", content: "Briefly explain the significance of the Rosetta Stone." }
],
temperature: 0.5,
max_tokens: 150
});
try {
const response = await fetch(A4F_CHAT_COMPLETIONS_URL, {
method: "POST",
headers: headers,
body: body,
// signal: AbortSignal.timeout(60000) // Node.js 16+ for timeout
});
if (!response.ok) {
const errorData = await response.json().catch(() => ({ error: "Failed to parse error JSON" }));
throw new Error(`API request failed with status ${response.status}: ${JSON.stringify(errorData)}`);
}
const data = await response.json();
console.log("Successful Response:");
// console.log(JSON.stringify(data, null, 2)); // Pretty print
if (data.choices && data.choices.length > 0) {
console.log("Assistant:", data.choices[0].message?.content);
} else {
console.log("No choices found in response:", data);
}
} catch (error) {
console.error("Failed to call A4F API:", error);
}
}
callA4FDirectly();

cURL

export A4F_API_KEY="YOUR_A4F_API_KEY"
curl -X POST https://api.a4f.co/v1/chat/completions \
-H "Authorization: Bearer $A4F_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "provider-1/chatgpt-4o-latest",
"messages": [
{"role": "user", "content": "Translate 'Hello, world!' to Spanish."}
],
"temperature": 0.3
}'

Handling Responses

A successful API call (HTTP status 200 OK) will return a JSON response compatible with the OpenAI API. This includes fields like id, model, choices (containing the assistant's message), and usage (token counts).

Your client code should parse this JSON to extract the required information, typically the content of the assistant's message from choices[0].message.content.

Streaming with Direct API Calls

To stream responses directly, set "stream": true in your JSON payload. The server will respond with a stream of Server-Sent Events (SSE). Each event will be a line starting with data: followed by a JSON object (a chunk of the completion), and the stream terminates with data: [DONE].

Handling SSE streams requires specific client-side logic to parse the incoming data chunks. Many HTTP libraries provide ways to iterate over response lines or chunks for streaming. Refer to the Streaming documentation for more detailed examples and considerations for parsing SSE.

Error Handling

If an API request fails, A4F will return an HTTP error status code (e.g., 400, 401, 429, 500) and a JSON body with error details. Your client code should check the HTTP status code and parse the JSON error response. See the Errors documentation for common error codes.

When to Use Direct API Calls

  • When working in a language or environment where a suitable OpenAI-compatible SDK is unavailable or undesirable.
  • When you need fine-grained control over HTTP request details (e.g., specific timeout configurations, custom retry logic not offered by an SDK).
  • For lightweight integrations or scripting where including a full SDK might be overkill.
  • When you need to set custom HTTP headers that an SDK might not easily expose (refer to Setting Headers).

Was this page helpful?