Protecting API Keys and Handling HTTP Status Codes When Calling LLM APIs from C++
This article explains how to keep API keys out of terminal history and log files while debugging C++ requests to LLM APIs. It also covers how to interpret common HTTP status codes, retry safely, and structure a C++ client for OpenAI-compatible chat APIs.
7.5 Protecting API Keys During Debugging
Developers often print entire request headers while debugging. This exposes API keys in terminal history and log files. Log only the request URL, model name, HTTP status code, and latency. If you must print the key to troubleshoot, keep only the last four characters and replace the rest with asterisks:
std::string MaskApiKey(const std::string& key) {if (key.size() <= 4) {return std::string(key.size(), '*');}return std::string(key.size() - 4, '*') + key.substr(key.size() - 4);}
7.6 Meaning of HTTP Status Codes
A non-2xx status code usually means the request has a problem. Common causes and fixes are listed below.
| Status Code | Common Cause | How to Handle It |
|---|---|---|
| 400 | Malformed request body, such as a misspelled field name or a wrong data type | Check the JSON structure. Do not retry. |
| 401 | The API key is invalid or missing | Check the environment variable and the spelling of the request header. |
| 429 | The request rate or quota limit has been exceeded | Wait, then retry with exponential backoff. |
| 5xx | A server-side error | Retry later. If the request still fails, log the error. |
The exact meaning of each status code is defined in the official documentation. You can retry 429 and 5xx responses. Double the wait time after each attempt, and set a maximum number of retries to prevent endless requests.
8. Summary
This article described the main steps for calling a chat API compatible with the OpenAI protocol from C++. The key points are:
- Protocol compatibility: Most mainstream cloud LLM services support the OpenAI protocol. The same request format works with several platforms. Switching platforms mainly requires changing the Base URL and the model name.
- Key management: The API key is sent in the
Authorizationheader and read from an environment variable. It should not be written into source code or logs. - Resources and security: Free the libcurl header list and handles after use. Enable certificate verification in production, and set both connection and overall timeouts.
- Streaming parsing: SSE events start with
data:. A network chunk can split a line, so keep the leftover buffer between reads. Stop receiving only after[DONE]arrives. - Engineering wrapper: Place network calls in a separate module. Handle status codes, retries, and timeouts in that module, so business code only calls business-level interfaces.
C++ remains widely used in high-performance server software, embedded systems, and game engines. Knowing how to make HTTP calls and parse JSON lets you add LLM capabilities to these systems.
