An AI API is the interface that lets your application use language models from providers such as OpenAI, Anthropic or Google through an HTTP request. Your app sends text and the model sends back a response. A first prototype can be running in an afternoon. The real work is getting that prototype ready for production: key security, error handling, cost and safety.
What Is an AI API?
An AI API lets you run a large language model on the provider's servers and get the result back, without hosting the model yourself. You pay for the tokens you use. Training, hardware and scaling stay with the provider. What's left for you is feeding the model the right data and connecting its output safely to your workflow.
General API integration principles still apply. I cover basics like authentication, timeouts and retries in the API integration guide. This post focuses on what's specific to language models.
Before You Start: Choosing a Provider and Model
Choose a model based on your own work, not on public leaderboards. Build a small test set from real examples, run a few models against it and compare accuracy, speed and cost side by side. For tasks that need multi-step decisions, reasoning models can be more accurate, but they're slower and cost more. To estimate a monthly budget up front, use the formula in the guide to LLM API costs.
If your users write in a language other than English, build the test set in that language. A model's results in English don't always carry over.
Keep Your API Key Safe
Your API key is the key to your bill. OpenAI's production best practices guide (opens in a new tab) advises against putting keys in code or public repositories and recommends passing them to your app through environment variables or a secret management service. The same guide recommends using a project service account as your application's identity rather than one developer's key, and setting an expiration date on keys.
The most common mistake is putting the key in code that runs in the browser or a mobile app. Anything there ends up in the user's hands. Always send requests through your own server. The server authenticates the user, limits how many requests they can make and only then calls the provider.
What a Request Looks Like
Details differ between providers, but most requests include the same parts: which model to use, instructions that set the model's role and rules, the user's message or conversation history, and a maximum number of tokens to generate.
// Server side: the key comes from an environment variable and never reaches the browser
const response = await client.responses.create({
model: process.env.AI_MODEL, // don't hard-code the model name
instructions: "You are a customer support assistant. Answer briefly and politely.",
input: userMessage,
max_output_tokens: 800,
});
console.log(response.output_text);This example has two small habits worth copying. The model name comes from an environment variable, so switching models doesn't require a deploy. And there's an output token cap, which stops unexpectedly long answers from inflating the bill.
For long answers, stream the response so users aren't left waiting. Providers mostly use server-sent events (SSE) for this. I compare that approach with WebSockets in the post on WebSocket vs SSE.
Structured Output: Connecting Responses to Code
If the model's answer feeds another system, ask for JSON that follows a schema instead of free text. OpenAI's structured outputs guide (opens in a new tab) explains that the older JSON mode only guarantees valid JSON, while structured outputs also guarantee that the response matches your schema, and it recommends using structured outputs whenever possible.
Matching the schema doesn't make the content correct. You know the fields arrive with the right types, but you still need to check the values against your own business rules. The post on structured output for LLMs goes into the details.
Tool Calling: Letting the Model Use Your App
Tool calling (also called function calling) is when the model, while answering, says it wants to use one of the functions you've defined. OpenAI's function calling guide (opens in a new tab) describes a function definition as a way for the model to pass data to your application, where your code accesses data or takes the action. The guide's examples include checking the weather, looking up a user's account details and issuing a refund for a lost order.
The flow works like this:
- You send the request along with the tools the model may use and their parameters.
- If needed, the model replies with the tool it wants to call and the arguments.
- Your code validates the arguments, runs the action and sends the result back to the model.
- The model uses that result to write its answer to the user.
Step three matters most. Don't execute hard-to-reverse actions like refunds straight from the model's request. Check the user's permissions, cap amounts and ask for human approval where it makes sense.
Handle Errors and Rate Limits
Every provider enforces rate limits, and in production you will hit them. OpenAI's rate limits guide (opens in a new tab) explains that limits are tracked with several measures, such as requests per minute (RPM) and tokens per minute (TPM), and whichever fills first applies. When you exceed a limit, the API returns a 429 error. If the response includes a Retry-After header, the guide says to wait at least that long. Without one, fall back to exponential backoff with a small random delay so clients don't all retry at once.
Anthropic's picture is similar. Anthropic's API errors documentation (opens in a new tab) says a 529 code means the API is temporarily overloaded because of high traffic across all users, and that its official SDK retries connection errors, rate limits and 5xx errors twice by default, with exponential backoff.
On top of that:
- Set a timeout on every request. Streaming makes it easier to keep long responses alive.
- Cap retries so you never loop forever.
- When the provider doesn't respond, show the user a clear message or fall back to another model.
- Set daily or monthly usage limits per user.
Security: Prompt Injection
The most important risk specific to LLM applications is prompt injection. OWASP's LLM01:2025 prompt injection page (opens in a new tab) defines it as user input that changes the model's behavior or output in unintended ways. The attack text doesn't even have to be visible to people, as long as the model reads it. An instruction hidden in a web page the model is asked to summarize, for example, can steer it the wrong way.
No single measure removes this risk. Limit the tools and data the model can reach to the minimum it needs, treat the model's output like untrusted user input and require human approval for critical actions. I go deeper in the post on prompt injection, and cover general web security in the OWASP Top 10 guide.
Monitor Quality and Cost
Once you're live, log at least the following for every request: the model used, input and output token counts, response time and error status. Those logs explain the bill and show you where to look when something breaks. If the text includes personal data, think about retention periods and masking before you store it.
Keep the test set you built at the start. Rerun it every time you change the instructions, the model or the data. Providers update models often, and a version change can quietly affect answer quality.
Finally, avoid tying yourself tightly to one provider. Keeping all model calls in a single module makes a later switch of model or provider a few-line change.
Frequently Asked Questions
Can I call an AI API directly from the browser?
Not with a long-lived API key. Browser code is visible to anyone, and your key can easily be taken from there. Route requests through your own server.
Which programming language should I use?
Major providers offer official SDKs for many languages, Python and JavaScript/TypeScript in particular. SDKs handle things like retries for you, so prefer them over raw HTTP where you can.
Will the provider use my data for training?
It depends on the provider and your agreement. Read the provider's data usage and retention terms before integrating, and settle the legal basis if you'll be sending personal data.
How much does an AI API cost?
It depends on the model and the number of tokens you use. The most reliable estimate comes from measuring tokens per request on real examples and multiplying by your monthly request volume.
To connect AI APIs to your existing system safely, see the AI and LLM integration service or tell me about your project on the contact page.



