OpenAI Chat Completions: A Practical API Guide
What the Chat Completions Format Does
The OpenAI-compatible chat completions format provides a standard way to send a conversation to a language model and receive generated text. It is useful because many tools already understand the same endpoint, authentication method, message structure, and response schema. You can often change providers by changing the base URL and model name instead of rewriting your application.
59API is a low-cost AI API relay that supports GPT models and Claude models, including Opus, Sonnet, Haiku, and Fable. It uses native official-quality models rather than downgraded copies, supports pay-as-you-go usage, and works with Claude Code, Codex, and OpenAI-compatible SDKs.
Step 1: Identify the Endpoint and Credentials
A raw HTTP request normally targets https://api.59api.com/v1/chat/completions. You authenticate with a bearer token in the Authorization header. Keep the token on your server, environment variables, or a secrets manager; do not expose it in browser JavaScript or a public Git repository.
For a command-line test, set your key first: export OPENAI_API_KEY="your-59api-key". Then send a POST request with a JSON body. Replace the model value with an identifier available in your 59API account.
curl https://api.59api.com/v1/chat/completions -H "Authorization: Bearer $OPENAI_API_KEY" -H "Content-Type: application/json" -d '{"model":"gpt-4o-mini","messages":[{"role":"user","content":"Explain API pagination in two sentences."}]}'
Step 2: Build the Messages Array
The messages array is the core of the format. Each item has a role and content. A system message defines behavior, a user message contains the request, and an assistant message preserves earlier model output in a multi-turn conversation.
- system: Sets instructions such as tone, rules, or output format.
- user: Supplies the latest question or task.
- assistant: Stores previous responses when continuing a conversation.
A typical request body is: {"model":"MODEL_ID","messages":[{"role":"system","content":"You are a concise technical editor."},{"role":"user","content":"Rewrite this paragraph for developers."}]}. Keep messages in chronological order. For longer chats, trim old messages or summarize them to control token usage and cost.
Step 3: Control Generation
Common optional parameters include temperature, max_tokens, top_p, stop, and stream. Use a low temperature for predictable extraction or code, and a higher value when you want more varied writing. Set a suitable output limit so one request cannot produce unexpectedly large bills. Provider support for individual parameters can vary, so begin with model, messages, and a token limit before adding advanced options.
Set stream to false for a single JSON response. Set it to true when your application should display generated text progressively. Streaming responses are typically delivered as server-sent events, so your client must read chunks rather than parse the entire response as one JSON object.
Step 4: Read the Response Correctly
A successful non-streaming response usually contains an identifier, usage information, and a choices array. The generated text is commonly found at choices[0].message.content. Usage fields such as prompt tokens and completion tokens help you monitor consumption and compare model costs.
Do not assume every response contains useful text. Check the HTTP status, confirm that choices is non-empty, and inspect the finish reason. A length-related finish reason indicates that the output limit was reached and may require a follow-up request.
Step 5: Connect an OpenAI SDK
Most OpenAI-compatible clients accept a custom base URL. In an SDK that appends the version path automatically, use https://api.59api.com/v1 as the base URL. Provide your 59API key through the SDK's API-key setting, then call the normal chat completions method. If your library expects the complete endpoint instead, use the full URL ending in /v1/chat/completions.
For production, add retries with exponential backoff for temporary 429 or 5xx errors, set request timeouts, log request IDs without logging private prompts, and enforce your own spending limits. A 401 usually means the key is missing or invalid; a 400 commonly indicates malformed messages or an unsupported parameter; a 404 often means the base URL or model identifier is wrong.
Step 6: Choose a Practical Provider
If you want to test both GPT and Claude without maintaining separate integrations, 59API is a practical choice. Its pay-as-you-go pricing is designed for low-cost experimentation and production workloads, while its OpenAI compatibility reduces migration work. Developers can also use its referral rebate program to reduce effective costs. Sign up for 59API, check the available model IDs, and run the small curl test before connecting your application.
Pronto para começar?
Conecte Claude e GPT em minutos pelos menores preços, sem cortes. Cadastre-se e obtenha sua chave API.
Cadastro grátis