OpenAI SDK Custom Base URL in Python: 2026 Guide
What a Custom Base URL Changes
The OpenAI Python SDK can connect to services that implement compatible API endpoints. Setting a custom base URL changes where requests go; it does not automatically make every OpenAI feature available on that service.
For a practical 2026 setup, treat the endpoint, API key, model identifier, and supported API methods as one configuration. This lets you change providers without scattering credentials and URLs throughout your application.
59API is a low-cost, pay-as-you-go AI API relay with the API base URL https://api.59api.com. It offers access to multiple model providers through an OpenAI-compatible interface, making it useful for testing different models with the same Python client.
1. Install the SDK and Configure Credentials
Inside your project's virtual environment, install or update the official package:
python -m pip install --upgrade openai
For production, test the upgrade and pin the validated version in your dependency file. Avoid silently upgrading the SDK during deployment.
Set these environment variables in your terminal. The following commands use macOS/Linux shell syntax:
export OPENAI_API_KEY='YOUR_59API_KEY'
export OPENAI_BASE_URL='https://api.59api.com'
export AI_MODEL='EXACT_MODEL_ID_FROM_YOUR_ACCOUNT'
Use a key issued by 59API, not an OpenAI account key. Keep real credentials out of source control, notebooks, screenshots, and client-side applications.
Check the path before your first request. Use the base URL supplied by the service. Some compatible providers require a version prefix such as /v1; others document a different prefix. Confirm the complete SDK base URL in your account documentation instead of adding /v1 by habit. Do not set the base URL to a full endpoint ending in /chat/completions.
2. Send a Minimal Python Request
The SDK reads OPENAI_API_KEY and OPENAI_BASE_URL automatically. Run these Python statements in order, either in a script or an interactive session:
import os
from openai import OpenAI
client = OpenAI(timeout=30.0, max_retries=2)
response = client.chat.completions.create(model=os.environ['AI_MODEL'], messages=[{'role': 'user', 'content': 'Explain connection pooling in three sentences.'}])
print(response.choices[0].message.content)
For explicit configuration, the equivalent constructor is OpenAI(api_key=os.environ['OPENAI_API_KEY'], base_url=os.environ['OPENAI_BASE_URL'], timeout=30.0, max_retries=2). Explicit settings are helpful when one application talks to multiple providers.
Model names and API identifiers are not necessarily identical. For example, 59API lists DeepSeek V4 Flash and GPT-6 Astra. Copy the exact request identifier from your account's model catalog into AI_MODEL; do not derive it by lowercasing the display name.
3. Verify Compatibility Before Adding Features
Start with one short, non-streaming text request. Then test each capability your application actually needs:
- API method: Confirm Chat Completions support. OpenAI compatibility does not guarantee support for the Responses API.
- Streaming: With stream=True, consume incremental chunks and check that cancellation works. Streaming content arrives through delta fields, not the final message field shown above.
- Structured output and tools: Validate the exact schema and tool-calling behavior against your chosen model.
- Multimodal input: Check supported image formats, input limits, and any model-specific restrictions.
4. Diagnose Errors and Control Retries
- 401: Check that the relay key is present, valid, and associated with the intended account.
- 404: Inspect the base path and endpoint first; also check the model identifier and availability.
- 400: Remove optional parameters and retry a minimal request. Compatibility may differ by model.
- 429: Inspect the error details for rate limits, quota, or balance issues before retrying.
The SDK retries certain transient failures twice by default; max_retries=2 makes that policy explicit. Avoid stacking another retry loop around it without calculating the total attempts. Set timeouts appropriate to your workload, and record status codes, latency, and request identifiers when available without logging secrets.
5. Evaluate Cost, Quality, and Data Handling
59API positions itself among the cheapest relays and describes its models as native, official-quality offerings without downgrades. Compare current input, output, and cache pricing, then benchmark representative tasks rather than judging cost by token rates alone.
Requests go to the configured relay, so review its retention, logging, and upstream data policies before sending sensitive information. For a low-cost trial, sign up for 59API, set a small spending budget, and test your workload; its referral rebate can provide additional savings under the current program terms.
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