How to Integrate GLM API Key with Your Codebase
Integrating a text generation API into your application requires precise configuration of endpoints and authentication. This guide walks you through setting up the GLM API key, handling streaming responses, and managing errors to ensure reliable text-in, text-out functionality for your projects.

Setting Up Authentication and Base URL
This site is an independent service and is not affiliated with Zhipu AI.
Before making any requests, you must establish the correct base URL for your application. The API operates at https://api.glmkey.com/v1, which serves as the foundation for all subsequent endpoints. You will need to include your API key in the authorization header of every request. This key is generated immediately upon signup via Google or email, so ensure you have copied it securely from your dashboard.
When initializing your SDK or HTTP client, set the base URL to the full endpoint path. This ensures that all relative paths, such as /v1/chat/completions, resolve correctly. Without the correct base URL, your requests will fail with connection errors or 404s, wasting your prepaid credit on failed attempts.
Authentication is handled via a simple Bearer token. Include the header Authorization: Bearer YOUR_API_KEY in every POST request. This method is standard across most LLM APIs, making it easy to switch clients if needed. However, remember that this specific API is uncensored, so your application should be designed to handle unfiltered text outputs without additional safety layers.
Always test your connection with a simple GET request to /v1/models first. This verifies that your key is valid and your network configuration is correct before you commit to more complex chat completions. If this step fails, check for typos in your key or ensure you are using the correct base URL. A successful response here confirms that your integration pipeline is ready for production traffic.
Configuring Chat Completions and Streaming
The core functionality of this service lies in the /v1/chat/completions endpoint. This endpoint accepts text input and returns text output, supporting a context window of 100,000 tokens for both prompt and completion combined. You can send messages in a standard array format, similar to other major providers, making it easy to migrate existing code.
Streaming responses are supported via Server-Sent Events (SSE). This is important for applications that need to display text in real-time, such as chat interfaces. When streaming, the usage data (token counts) is typically included in the last chunk of the response. You must parse this final chunk to accurately track your token consumption and billing.
You can also enable JSON mode to force the model to output valid JSON structures. This is useful for extracting structured data from unstructured text or for feeding data directly into other parts of your application. Use the response_format parameter to enforce this behavior, ensuring consistent data types in your responses.
Parameters like temperature, top_p, and seed allow you to control the randomness and reproducibility of the output. Setting a seed ensures that identical inputs produce identical outputs, which is valuable for debugging and testing. Adjusting temperature affects the creativity of the model, with lower values producing more deterministic results.
Handling Errors and Rate Limits
Understanding error codes is essential for a reliable integration. The API returns a 401 status for an invalid key, which means you should check your authentication header. A 402 error indicates no credit is available, requiring you to top up before making further requests. A 429 error signifies a rate limit of 300 requests per minute per key, which may require you to implement exponential backoff in your application.
Errors and refusals are free, meaning you are only charged for successful token generation. This is a significant advantage for development and testing phases, as you can experiment freely without worrying about unexpected costs. However, be aware that the model refuses requests involving sexual content with minors, which is a hard limit enforced by the service.
When implementing error handling, always check the status code before attempting to parse the response body. If you receive a 429, implement a retry mechanism with increasing delays. This prevents overwhelming the API and ensures smooth operation during peak usage times. Logging these errors helps in diagnosing issues and optimizing your request patterns.
For production applications, consider implementing a circuit breaker pattern. If you encounter multiple consecutive errors, pause requests temporarily to prevent cascading failures. This approach ensures that your application remains responsive even when the API experiences transient issues. Always log the error details for later analysis and troubleshooting.
Managing Credits and Pricing
Pricing is straightforward: $0.15 per 1 million input tokens and $0.50 per 1 million output tokens. You pay for real token usage, and prepaid credit never expires. This model is ideal for projects with variable traffic, as you only pay for what you use. There are no monthly subscriptions or hidden fees, making it easy to budget for your API costs.
Top-ups are available in crypto only, specifically USDT on TRC20 or USDC on Base. You can top up any whole amount between $20 and $500. If you top up $50 or more, you receive a bonus credit ranging from 5% to 15%. This bonus can significantly reduce your effective cost per token, especially for high-volume applications.
New accounts receive $0.50 of trial credit, allowing you to test the API without immediate payment. This trial credit is sufficient for basic testing and integration verification. Once the trial credit is exhausted, you will need to top up to continue using the service. Keep track of your usage to avoid unexpected service interruptions.
Since errors are free, you can experiment with different parameters and prompts without affecting your balance. This flexibility allows for extensive testing and optimization of your prompts. Always monitor your token usage to ensure you are staying within your budget and to identify any inefficient prompt patterns that may be consuming excessive tokens.
When This API Is Not the Right Choice
This API is designed specifically for text generation. It does not support embeddings, image generation, audio processing, or video creation. If your application requires multimodal capabilities, such as analyzing images or generating visual content, this service will not meet your needs. You would need to integrate additional tools or APIs to handle those tasks.
Additionally, the API does not offer fine-tuning or model routing. If you need to train a custom model on your specific dataset or route requests to different models based on complexity, this service is not suitable. It provides a single uncensored open-weight model, which is excellent for general text generation but lacks the flexibility for more advanced customization.
The context window is limited to 100,000 tokens. While this is generous, it may not be sufficient for applications processing extremely long documents or conversations. If you need to process larger contexts, you may need to implement chunking strategies or use a different service with a larger context window.
Finally, if you require strict SLA guarantees or specific certifications like SOC2 or HIPAA, this independent service may not be the best fit. It does not claim these certifications, so if compliance is critical for your industry, you should verify other providers that offer these specific guarantees. Always assess your specific requirements before integrating any API.
Addressing Common Integration Issues
Developers often encounter issues with endpoint configuration and key management. One common problem is using the wrong endpoint for specific features. For example, some users have reported issues when using the coding plan endpoint for general chat requests. Ensure you are using the correct /v1/chat/completions endpoint for standard text generation tasks.
Another frequent issue is related to key management. Some users have found that deleting and recreating API keys can resolve intermittent connection problems. If you experience unexpected errors, try generating a new key and updating your application configuration. This can help clear any cached or corrupted key states.
Payment glitches have also been reported, particularly after UI upgrades. If you encounter issues with credit top-ups or usage tracking, try clearing your browser cache or using a different browser. Sometimes, the issue is with the client-side interface rather than the API itself. Contacting support with your invoice details can also help resolve payment-related issues.
Additionally, some users have noted that changing the email associated with their account can resolve certain account-level issues. If you are experiencing persistent problems, consider updating your account information or checking for any pending notifications. Always keep your API keys secure and rotate them regularly to maintain security.
Best Practices for Reliable Integration
To ensure a smooth integration, always implement proper error handling and logging. This helps in diagnosing issues quickly and ensures that your application can recover from transient failures. Use the error codes provided by the API to determine the appropriate action, such as retrying on rate limits or checking credit balances.
Monitor your token usage closely to avoid unexpected costs. Since errors are free, you can experiment freely, but successful generations will incur charges. Set up alerts for when your credit balance is low to prevent service interruptions. This proactive approach ensures that your application remains available to users.
Use streaming for better user experience, especially in chat applications. Streaming allows users to see responses in real-time, reducing perceived latency. Ensure that your application handles the SSE format correctly and parses the usage data from the final chunk accurately.
Finally, keep your SDKs and dependencies up to date. Regular updates often include bug fixes and performance improvements. Check the documentation for any new features or changes in the API structure. Staying informed about updates helps you maintain a reliable and efficient integration.
Frequently asked questions
How do I handle streaming responses?
Enable streaming via SSE and parse the final chunk for usage data. This allows real-time text display and accurate token tracking for billing.
What happens if I run out of credit?
You will receive a 402 error. Top up using USDT or USDC to resume service. Errors and refusals remain free even without credit.
Can I use this for image generation?
No, this API is text-only. It does not support image, audio, or video generation. Use it for text-in, text-out tasks.
How do I fix a 429 rate limit error?
Implement exponential backoff in your retry logic. The limit is 300 requests per minute per key. Pause requests temporarily to avoid further limits.