How to Integrate Our Cloud TTS API into Python Applications?

By Okbajje editorial team · Updated 2026-11-19

This guide details the integration of the Okbajje Systems text-to-speech API into Python applications, targeting product teams developing assistive devices and elderly care solutions. You will learn to configure the client, manage audio payloads, and handle errors with precision. The API uses standard HTTP requests, ensuring consistent output for critical communication tasks where latency and accuracy are paramount.

Readers will find concrete examples for generating speech from text, saving audio files, and monitoring usage. The instructions cover voice selection, speed adjustment, and long-text splitting, all aligned with the specific needs of assistive technology workflows. No external SDKs are required; standard libraries or the OpenAI-compatible client work directly with our base URL.

How to Integrate Our Cloud TTS API into Python Applications?

Frequently asked questions

What Python version is required?

The API uses standard HTTP requests, so any Python version capable of making HTTP calls is sufficient. No specific version is mandated. We recommend using the OpenAI Python SDK or the requests library for straightforward integration. Since the endpoint follows the OpenAI speech API shape, your existing Python infrastructure can adapt easily without version-specific constraints.

How do I store the API key?

Store your key in environment variables or a secure configuration file. Pass it via the Authorization: Bearer tts-... header in each request. Since each account holds only one active key, ensure it is protected. If compromised, issue a new key immediately via the dashboard; the old key stops at once.

Can I stream audio directly?

No, streaming is not supported. The API returns the complete audio file in the response body after synthesis finishes. You must wait for the full file to be generated before processing or playing it. This ensures consistent audio output for critical communication tasks where latency and accuracy are paramount.

How do I handle rate limits?

The limit is 60 requests per minute per key. If you exceed this, requests may queue or fail. Monitor your usage via the dashboard. For higher throughput, implement exponential backoff in your Python code to handle transient errors gracefully without overwhelming the endpoint during peak usage periods.

Is the API suitable for real-time use?

It is suitable for near real-time use, but not instantaneous. Synthesis takes roughly one second per 25 characters. Requests are processed sequentially, so under load, delays may occur. For assistive devices, ensure your application buffers audio to mitigate these slight delays during generation.

How do I split long texts?

Split input text into chunks of up to 4096 characters. Send each chunk as a separate POST request. Join the resulting audio files client-side. This approach ensures compliance with the character limit per request while allowing you to generate audio for longer documents or instructions.

What libraries are recommended?

Use the official OpenAI Python SDK or the requests library. Since the endpoint matches the OpenAI speech API shape, you can use the OpenAI SDK by changing the base_url to https://api.okbajje.cc/v1. This allows you to leverage existing SDK features for authentication and error handling.

How do I debug failed requests?

Check the HTTP status code and response body for error details. Failed requests are free, so no charge is incurred. Review your input text length and voice selection. If the error persists, verify your API key is active and not expired. Use the dashboard to check recent usage logs for context.

Can I use asyncio?

Yes, you can use asyncio with the requests library or an async-compatible HTTP client like aiohttp. Since requests are processed sequentially on our end, concurrency is managed by your client. Ensure your code handles rate limits appropriately to avoid throttling when making concurrent requests from your application.

How do I manage multiple keys?

Each account holds only one active key at a time. To manage keys, issue a new one via the dashboard; the old key stops immediately. You cannot use multiple keys simultaneously from a single account. For separate workloads, consider creating distinct accounts, each with its own key and balance.

Is SSL required?

Yes, use HTTPS for all requests to https://api.okbajje.cc/v1. SSL ensures secure transmission of your API key and text data. The endpoint requires secure connections, so standard HTTPS libraries in Python will handle this automatically when you specify the correct scheme in your base URL.

How do I test locally?

Use the provided curl example or the OpenAI SDK with the custom base URL. Send a small text payload to verify the response format. Check that the audio file is generated correctly. Use the free trial credit ($0.50) to test without consuming your main balance during development and integration phases.

What is the max concurrent requests?

The API processes requests sequentially. While you can send multiple concurrent requests from your client, they will be queued on our side. The rate limit is 60 requests per minute. Ensure your application handles queueing and backoff to maintain smooth operation for assistive device audio generation tasks.

Can I cache audio responses?

Yes, cache audio responses locally if the same text and voice are used frequently. Since generated audio is not stored on our servers, caching improves performance for repeated phrases. Ensure your cache key includes the voice, speed, and language parameters to avoid serving incorrect audio variations.

Prerequisites

Sound wave illustration for: Prerequisites

Python 3.8 or later is required. Standard libraries such as requests or urllib handle the HTTP communication, while pydub or simpleaudio manage audio playback and file handling. These tools ensure stable integration with assistive device applications and elderly care software stacks.

Python Version

Python 3.8+ is the minimum supported version. This ensures compatibility with the TTS engine and allows efficient memory management for audio processing in embedded assistive devices or elderly care monitoring systems.

  • Python 3.8 or higher
  • Standard library support for JSON and HTTP

HTTP Libraries

Use requests for synchronous calls or httpx for async operations. These libraries handle the JSON payload construction and binary response parsing required for sending text to https://api.okbajje.cc/v1/audio/speech.

  • requests for standard synchronous integration
  • httpx for concurrent processing in multi-device setups

API Key Setup

Generate your key at /get-api-key/. Pass it via the Authorization: Bearer tts-... header. Keys are single-active; issuing a new one invalidates the previous one immediately, which is critical for secure assistive device deployments.

  • One active key per account
  • Invalidate old keys instantly upon new issuance

Client Configuration

Sound wave illustration for: Client Configuration

Configure the client to route requests to the correct endpoint. Ensure the base URL points to our API infrastructure for reliable connectivity.

Base URL Setup

Set the base URL to https://api.okbajje.cc/v1. This directs all POST and GET requests to the correct service endpoint. Verify connectivity before processing audio.

Authorization Header

Include the header Authorization: Bearer <your-api-key> in every request. Use the key issued at /get-api-key/. A single active key authenticates all calls.

  • Header: Authorization: Bearer tts-...
  • One active key per account
  • Replace old keys immediately if rotated

Timeout Settings

Set connection and read timeouts to handle network latency. Short phrases generate in seconds; longer texts may wait in a queue. Adjust timeouts to prevent premature disconnection during high-load periods.

  • Set reasonable read timeouts
  • Account for queueing delays
  • Monitor for timeout errors

Making Requests

Sound wave illustration for: Making Requests

The API accepts a JSON body with standard fields. Include the text, model, voice, and optional parameters like speed and language. Keep input under 4096 characters to ensure reliable synthesis.

Send the request using a standard HTTP POST to the speech endpoint. The server processes the text and returns the audio file in the specified format, such as MP3 or WAV.

JSON Payload

Structure your request body with the input text, model (tts-1 or tts-1-hd), and voice identifier. You may also specify response_format (mp3, wav, opus, flac, pcm) and speed (0.25–4.0). The language field is optional but recommended for non-English Latin text to prevent incorrect language guessing.

Ensure the input text does not exceed 4096 characters. If your text is longer, split it into chunks before sending individual requests.

  • input: The text to synthesize
  • model: 'tts-1' or 'tts-1-hd'
  • voice: One of 8 presets (e.g., 'aria', 'atlas')
  • response_format: mp3, wav, opus, flac, or pcm
  • speed: Float between 0.25 and 4.0
  • language: Optional ISO code

POST Request

Use any standard HTTP client library. Send a POST request to https://api.okbajje.cc/v1/audio/speech. Include the Authorization header with your Bearer token in the format Bearer tts-....

The request is processed synchronously. For elderly care devices, ensure your client handles the response efficiently, as latency can vary based on queue load.

  • Endpoint: POST https://api.okbajje.cc/v1/audio/speech
  • Header: Authorization: Bearer tts-...
  • Content-Type: application/json

Binary Response

The response contains the raw audio binary data. Do not attempt to parse it as JSON unless an error occurs. Save the binary output directly to a file or buffer for playback in your assistive device application.

If the request fails, the response will be a JSON error object with a status code. Failed requests are free and do not charge your balance.

  • Response is binary audio data
  • Error responses are JSON
  • No JSON wrapper for success

Audio Handling

Sound wave illustration for: Audio Handling

The API returns raw audio bytes, requiring explicit handling for storage or playback. Ensure your application correctly interprets the binary response stream to preserve audio integrity across formats like MP3, WAV, or FLAC.

Efficient memory management is critical when processing multiple requests. Buffer data appropriately to avoid excessive RAM usage, especially when generating longer texts that may require chunked processing.

Saving Files

Write the binary response directly to disk using standard file I/O operations. This approach minimizes memory overhead and allows for immediate access to the generated audio file for assistive device playback.

  • Use binary write mode ('wb') to prevent encoding issues.
  • Validate file extensions match the requested response format.
  • Implement atomic writes to prevent corrupted audio files during interruption.

Playback Options

Load the saved audio file into a local media player library for immediate playback. This method is suitable for stationary assistive devices where low latency is not the primary constraint.

For real-time needs, consider streaming the bytes directly to a playback buffer if your library supports it.

  • Use libraries like PyAudio or pygame for local playback.
  • Ensure the audio format matches the device's decoder capabilities.

Memory Management

Read the response in chunks rather than loading the entire file into memory. This is essential for handling larger audio files generated from longer texts, ensuring stable performance on resource-constrained devices.

  • Process data in 4KB chunks.
  • Clear references to large byte objects after processing.

Error Handling

Sound wave illustration for: Error Handling

Robust error handling ensures that assistive devices and elderly care solutions maintain consistent audio output during critical communication tasks. By anticipating network variability and API constraints, product teams can prevent silent failures and ensure that synthesized speech is delivered reliably to end-users without unexpected interruptions or data loss.

Timeouts

Set explicit timeouts (e.g., 30 seconds) to prevent indefinite waits during synthesis. Short phrases take a few seconds; longer texts process at roughly real-time speed (25 characters per second). If the API queue is under load, requests may wait, so configure your Python client to handle delayed responses gracefully without hanging the user interface.

  • Use a 30-second timeout for standard requests.
  • Increase timeout for texts approaching the 4096-character limit.
  • Implement retry logic with exponential backoff for transient network errors.

Response Parsing

The API returns audio as binary data. Ensure your Python code reads the response content directly as bytes without attempting to parse it as JSON. This prevents encoding errors when saving the file or passing the audio stream to playback libraries. Always check the HTTP status code before processing the body to confirm success.

  • Read response.content as raw bytes.
  • Validate HTTP 200 status before parsing.
  • Avoid JSON decoding for binary audio responses.

Rate Limits

The API enforces a limit of 60 requests per minute per key (10 per minute before the first top-up). If you exceed this, the API returns a 429 error. Implement logic to pause and retry after the rate limit window resets. Monitor your usage dashboard to ensure your application’s request volume stays within these bounds to avoid service interruption.

  • Limit: 60 requests/minute per key.
  • Initial limit: 10 requests/minute.
  • Handle HTTP 429 errors with a retry mechanism.
  • Monitor usage via the /get-api-key/ dashboard.

Voice & Speed

Sound wave illustration for: Voice & Speed

Selecting the correct voice and speed parameters ensures audio output matches the operational context of assistive devices and elderly care systems. The API supports eight distinct presets, ranging from the warm narration of Aria to the neutral news style of Atlas, allowing product teams to tailor the auditory experience for specific user needs.

Voice Selection

Choose from eight licensed voices based on LibriTTS-R and LibriVox recordings. Each voice offers a distinct tone suitable for different communication tasks, such as instructional guidance or conversational updates. The system guesses the language from the script; for non-English Latin text, set the language explicitly.

  • Female voices: Aria (warm narrator), Nova (upbeat), Luna (storytelling), Sage (instructional).
  • Male voices: Felix (energetic), Milo (conversational), Atlas (neutral news), Orion (documentary).

Speed Adjustment

Adjust the playback speed between 0.25 and 4.0 using the speed parameter. This allows precise control over generation latency and listening duration, ensuring the audio remains clear and intelligible for elderly users or slow-processing assistive hardware. Standard speed provides a natural rhythm for critical communications.

Language Settings

Set the language field using an ISO code to ensure accurate synthesis, particularly for non-English Latin-script text. While the system guesses the language from the script, explicit setting prevents errors. The API supports 23 languages, including English, Spanish, German, and Japanese, ensuring broad compatibility for diverse care environments.

Testing

Sound wave illustration for: Testing

Testing ensures your integration handles latency and character limits correctly before deployment in assistive devices. Verify that text synthesis returns within acceptable timeframes for elderly care workflows.

Run local checks against the API endpoint to confirm audio file integrity and encoding compatibility with your hardware players.

Local Setup

Install the OpenAI Python SDK or requests library. Configure the base URL to https://api.okbajje.cc/v1 and set your Authorization header with your API key. Ensure your environment variable TTS_API_KEY is loaded securely.

  • Python 3.8+ recommended for stable async support.
  • Use requests for synchronous testing during development.
  • Verify network connectivity to api.okbajje.cc.

End-to-End Tests

Send a short text payload (under 100 characters) and verify the response contains a valid audio file in your chosen format (e.g., mp3 or wav). Check that the HTTP status code is 200 and the file size correlates with the input length. Confirm that the audio plays correctly on your target assistive device or playback hardware.

Test error scenarios by sending an empty input or exceeding the 4096-character limit to ensure proper error responses are returned without crashing your application.

  • Verify 200 OK status for successful synthesis.
  • Check file format matches response_format parameter.
  • Ensure audio duration matches text length expectations.

Benchmarks

Measure the time taken for a standard 100-character request. Expect generation to take a few seconds for short phrases, as requests are processed sequentially. Record this baseline to ensure your application’s timeout settings accommodate the queue latency under load.

Test with varying speeds (0.25–4.0) to confirm that speed adjustments do not introduce additional latency beyond the processing time. Document these metrics for your product team’s performance review.

  • Record average latency for 100-character inputs.
  • Test timeout settings against 5-second generation windows.
  • Log character count vs. file size ratios.
Testing

Deployment

Sound wave illustration for: Deployment

Deploying the TTS API in assistive device environments requires strict separation of configuration and code. Store your API key in environment variables to prevent accidental exposure during device updates or log exports. This ensures that critical communication audio generation remains secure without requiring code recompilation.

Security is paramount when handling audio for elderly care solutions. Use HTTPS for all API calls to protect data in transit. Regularly rotate keys via the dashboard if a device is lost or compromised, as the old key becomes invalid immediately.

Environment Variables

Define TTS_API_KEY in your deployment environment. Do not hardcode the key in your Python scripts, as logs may expose it during debugging. Use standard libraries like os.getenv to retrieve the value at runtime.

Ensure your deployment pipeline injects these variables before the application starts. This allows different configurations for testing and production environments without changing the application code.

  • Use os.getenv('TTS_API_KEY') in Python.
  • Exclude environment files from version control if they contain keys.
  • Verify variable presence before making the first API call.

Key Security

The API key authenticates all requests. Store it securely on the device or server. If the key is compromised, generate a new one immediately via the dashboard; the previous key stops working instantly.

Use HTTPS for all connections to api.okbajje.cc. This prevents interception of the key and the generated audio data during transmission to your assistive devices.

  • Rotate keys via the /get-api-key/ page.
  • Use HTTPS exclusively.
  • Do not log the key in plain text.

Usage Monitoring

Monitor your character usage and balance regularly. The API charges $0.01 per 1,000 characters. Track usage to predict costs and prevent service interruption due to insufficient balance.

Check the /v1/models endpoint to verify the available models. Ensure your application handles rate limits (60 requests per minute) by implementing appropriate retry logic with exponential backoff.

Log request metadata (time, status, characters) for billing audits. This helps identify unusual usage patterns that might indicate a loop or error in your audio generation pipeline.

  • Track character count per device.
  • Monitor balance for low funds.
  • Log request status codes for debugging.

Common Issues

Sound wave illustration for: Common Issues

Developers often encounter encoding mismatches when processing binary audio responses or passing non-ASCII text to the API. Ensuring correct UTF-8 handling prevents silent data corruption in assistive device logs.

Text input is strictly limited to 4096 characters per request. Exceeding this limit causes immediate rejection, requiring application-level splitting logic for longer passages.

Rate limits restrict usage to 60 requests per minute per key. Concurrent processes must manage queueing to avoid temporary service interruptions during peak generation periods.

Encoding Errors

Ensure all input strings are UTF-8 encoded before serialization. The API expects standard JSON; malformed bytes in the input field result in immediate failure without partial audio generation.

  • Use json.dumps() with ensure_ascii=False for non-Latin scripts.
  • Verify character count includes spaces and punctuation.

Payload Size

The input field accepts a maximum of 4096 characters. Requests exceeding this threshold return an error code without charge. Applications must implement chunking logic to handle longer texts, joining the resulting audio files sequentially.

  • Character limit is hard; no partial processing occurs.
  • Spaces and punctuation count toward the 4096 limit.

Concurrency

The API enforces a limit of 60 requests per minute per API key. Under load, requests are processed sequentially, potentially increasing latency. Implement exponential backoff or multiple keys to maintain throughput for critical communication tasks.

  • Limit: 60 requests/minute/key.
  • Requests queue if the limit is reached.

Long Texts

Sound wave illustration for: Long Texts

For assistive devices processing lengthy texts, the 4096-character limit per request requires splitting input into manageable segments. This ensures consistent synthesis without exceeding payload constraints.

Generated audio files must be joined to form a continuous output. The API processes requests sequentially, so long texts may experience slight latency due to queueing.

Text Splitting

Divide input text into chunks of up to 4096 characters. Each chunk triggers a separate synthesis request. This approach maintains stability for elderly care communication systems.

  • Max 4096 characters per request
  • Count spaces and punctuation
  • Split at natural sentence boundaries

Audio Joining

Concatenate the binary responses from each segment. Ensure the audio format remains consistent (e.g., MP3 or WAV) across all parts to prevent playback errors.

  • Maintain uniform response_format
  • Append files sequentially
  • Verify file integrity

Gap Minimization

Processing occurs one after another, potentially introducing gaps between segments. Minimize delay by optimizing request timing. The typical speed is roughly 25 characters per second.

  • Sequential processing applies
  • Latency varies with load
  • Real-time approximation for long texts

Security

Sound wave illustration for: Security

Security for assistive device deployments requires disciplined key management and strict network protocols. Okbajje Systems ensures all API communications occur over encrypted channels, protecting the integrity of audio synthesis requests in clinical and home care environments.

Key Storage

Store the single active Bearer token in environment variables rather than hardcoding it into application binaries. Rotate the key via the dashboard immediately upon suspicion of compromise, as the old key stops at once.

  • Use OS-level secure storage for device-bound applications
  • Regenerate keys via /get-api-key/ page
  • Avoid storing keys in version control systems

HTTPS

All requests to https://api.okbajje.cc/v1 must use HTTPS. This ensures that the text input and the resulting audio stream are encrypted in transit, preventing interception by unauthorized parties on local or cellular networks.

  • Enforce TLS 1.2 or higher
  • Validate certificate chains on embedded devices

Validation

Validate the input field length before transmission to ensure it does not exceed 4096 characters. Confirm the voice and response_format values against the /v1/voices endpoint to prevent malformed payloads from consuming request quota.

Scaling

Sound wave illustration for: Scaling

As usage grows, distribute load across multiple API keys to maintain throughput within the 60 requests per minute limit. Each key operates independently, allowing parallel generation for assistive devices or elderly care systems requiring consistent audio delivery.

Multi-Key

Assign distinct keys to different application instances or departments. Rotate keys as needed; issuing a new key immediately invalidates the previous one, so ensure no active requests are pending before rotation.

  • Generate new keys via /get-api-key/
  • Invalidate old keys instantly
  • Distribute keys across services

Growth Planning

Monitor character consumption against your USDT balance. Since there are no monthly plans, scale costs directly with usage. Plan top-ups for TRC-20 transfers to avoid service interruption during peak demand.

Cost Optimization

Split long texts into 4096-character segments to maximize efficiency. Failed requests incur no charge, so implement retry logic for transient errors. Use tts-1 or tts-1-hd as both have the same cost of $0.01 per 1,000 characters.

Listen to the 8 voices

Each sample below was generated by this API from the same sentence. Input text is not stored or used for training, ensuring that no long-term data drift affects voice consistency.

Avatar of the voice aria
ariafemale
Avatar of the voice nova
novafemale
Avatar of the voice luna
lunafemale
Avatar of the voice sage
sagefemale
Avatar of the voice felix
felixmale
Avatar of the voice milo
milomale
Avatar of the voice atlas
atlasmale
Avatar of the voice orion
orionmale

23 languages

Any voice speaks any of these languages.

Sources and further reading

  1. Wikipedia
  2. ISO 639 language codes
  3. W3C WAI: making audio and video accessible
  4. Python documentation
  5. openai-python on GitHub
  6. IETF RFC 7845: Ogg Opus
  7. openai-node on GitHub
  8. TRON developer hub: TRC-20
  9. Creative Commons Attribution 4.0
  10. Node.js documentation
  11. OpenAI API reference: create speech
  12. LibriTTS-R corpus (OpenSLR 141)

More on this site