AI APIs
Explain an API, identify the parts of an HTTP request, understand a typical model API workflow, and identify key security and governance controls.
##
- API in plain language
An API is a defined interface that lets one software component request a service from another. Think of a restaurant: the menu describes what can be requested, the order carries the request, the kitchen performs the work and the waiter returns the result. The analogy is limited, but it helps separate the interface from the implementation.
An AI application often follows this path:
User interface → application backend → model API/provider → model service → response → application validation → user interface
The browser should generally not hold a privileged provider API key. The backend should authenticate the user, enforce policy, protect secrets, apply limits and call the provider.
##
- Anatomy of an HTTP request
- Endpoint: the address of the service.
- Method: the operation, commonly POST for sending a generation request.
- Headers: metadata such as content type and authorisation.
- Body: structured request data, often JSON.
- Response: status code, headers and response body.
JSON is a text format for structured data using objects, arrays, strings, numbers, booleans and null. The provider defines the exact schema. Do not assume one provider's request format works unchanged with another.
##
- Example request pattern
The following is illustrative pseudocode. Replace the endpoint, authentication scheme and payload with the provider's current official API specification.
import os
import requests
api_key = os.environ["AI_API_KEY"]
response = requests.post(
"https://api.example.com/v1/generate",
headers={
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json",
},
json={
"model": "provider-model-id",
"input": "Summarise this policy excerpt."
},
timeout=30,
)
response.raise_for_status()
result = response.json()
print(result)Never commit keys to source control, expose them in frontend bundles, place them in logs or share them in prompts. Use a secrets manager or protected environment configuration, rotate keys and scope access where supported.
##
- Status codes and resilience
Common HTTP outcomes include 200-level success, 400-level client errors, 401 unauthorised, 403 forbidden, 404 not found, 429 rate limit and 500-level server errors. Exact provider behaviour varies.
Retries should be selective. A transient 429 or 503 may be retriable; a malformed request or permission failure usually is not. Use exponential backoff with jitter, a maximum attempt count and an overall deadline. For write operations, consider idempotency so retries do not duplicate side effects.
##
- Streaming, asynchronous work and cost
A synchronous request waits for a response. Streaming returns pieces as they are produced. Asynchronous workflows return a job identifier or otherwise allow work to continue outside the initial request. Streaming improves perceived responsiveness but does not guarantee lower total latency.
Costs may depend on input tokens, output tokens, model tier, tools, cached input, images, audio or other provider-specific units. Estimate costs from measured usage, not from request count alone.
##
- API security and governance
Risks include exposed credentials, excessive permissions, weak authentication, insecure tenant isolation, missing rate limits, sensitive logging, injection through request data, insecure callbacks and unsafe error handling.
Controls:
- keep provider credentials server-side
- authenticate and authorise each user action
- apply tenant-aware access checks
- validate request and response schemas
- classify and minimise transmitted data
- set timeouts, quotas and rate limits
- redact secrets and personal data from logs
- monitor errors, latency, usage and unusual patterns
- define provider retention, subprocessors and incident obligations
##
- Practical exercise
Draw the request path for an internal AI policy assistant. Mark where the user authenticates, where the API key is stored, where prompts are assembled, what data leaves the organisation and where logs are written. Identify at least five controls.
##
- Knowledge check
- What is an API endpoint?
- Why should a provider key not be stored in browser code?
- What does HTTP 429 commonly indicate?
- Why use bounded retries with jitter?
- What is the difference between streaming and asynchronous processing?
Answer key:
- The address of the API resource or operation.
- Browser code is accessible to users and attackers.
- Rate limiting.
- To reduce retry storms and bound resource use.
- Streaming delivers response chunks during generation; asynchronous processing separates job submission from completion.
##
- Checklist
- [ ] Use server-side secret storage.
- [ ] Authenticate and authorise requests.
- [ ] Validate inputs and outputs.
- [ ] Set rate, token, time and cost limits.
- [ ] Implement bounded retries and safe idempotency.
- [ ] Review logging, retention and data residency.
- [ ] Monitor provider errors and service changes.
##
- Further reading
Help improve this learning path.
Suggest a concept we should teach, or tell us what is unclear. No account is required. Email is optional and only for a reply. Do not include confidential or sensitive information.