What is an API and How to Use One
APIs Are the Building Blocks of Modern Software
Almost every application you use today is built on top of multiple APIs. When you check the weather on your phone, a weather API provides the data. When you log in with Google, OAuth APIs handle authentication. When you pay online, a payment API processes the transaction.
An Application Programming Interface (API) is a defined way for one piece of software to communicate with another. Instead of building everything from scratch, developers use APIs to access capabilities, data, and services built by other teams or companies.
For AI Automation Engineers, APIs are the primary way you access AI models. Companies like OpenAI, Anthropic, and Google do not give you the model itself -- they give you an API that lets you send prompts and receive responses.
How APIs Work: The Request-Response Model
Every API interaction follows the same basic pattern:
- Your application sends a Request to an API endpoint (a specific URL)
- The API server processes your request
- The API server sends back a Response with the result
This is identical to how a web browser works when you visit a website, except instead of requesting an HTML page, you are requesting data or a service.
The anatomy of an API request:
- Endpoint (URL): Where you send the request, e.g.
https://api.openai.com/v1/chat/completions - Method: What type of action (GET to retrieve data, POST to send data)
- Headers: Metadata including authentication credentials
- Body: The data you are sending (for POST requests) -- for AI APIs, this includes your prompt
- Authentication: A secret API key that proves you have permission to use the service
The anatomy of an API response:
- Status code: A number indicating success (200) or failure (400, 401, 500)
- Body: The returned data, almost always in JSON (JavaScript Object Notation) format
JSON: The Language of APIs
JSON is a lightweight data format used to structure information. Almost every modern API communicates using JSON. Here is an example:
{
"model": "gpt-4",
"choices": [
{
"message": {
"role": "assistant",
"content": "The capital of France is Paris."
},
"finish_reason": "stop"
}
],
"usage": {
"prompt_tokens": 15,
"completion_tokens": 8,
"total_tokens": 23
}
}
JSON uses key-value pairs ("key": "value"), arrays ([item1, item2]), and nested objects ({"nested": {"key": "value"}}). As an AI engineer, you will parse JSON responses to extract the information you need.
API Authentication: API Keys
Most AI APIs use API keys for authentication. An API key is a long, randomly generated string that uniquely identifies you and your usage. It looks like:
sk-proj-abc123xyz456...
Critical rules for API keys:
- Never share your API key publicly
- Never commit it to a public code repository (use environment variables)
- Treat it like a password -- anyone with your key can charge API calls to your account
- Rotate (replace) your keys regularly
In code, you pass the API key in the request header:
headers: {
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json'
}
Rate Limits and Quotas
API providers impose limits to prevent abuse and manage server load:
- Rate limits: Maximum requests per minute or per day
- Token limits: Maximum tokens per request or per minute
- Cost limits: Monthly spending caps
When you exceed a rate limit, the API returns a 429 (Too Many Requests) error. Good AI systems handle this gracefully with retry logic and exponential backoff.
REST APIs vs. Other API Types
Most AI APIs are REST (Representational State Transfer) APIs, which use standard HTTP methods and JSON. Other types exist (GraphQL, WebSocket, gRPC) but you will encounter them less frequently when working with AI services.
The key REST conventions to know:
- GET requests retrieve data
- POST requests send data and trigger actions (AI API calls are almost always POST requests)
- Authentication is typically in the header
- Responses are JSON
Making Your First API Call
Here is the structure of a basic AI API call using the fetch API in JavaScript (for a browser or Node.js environment):
// Run in Node.js (requires node-fetch or native fetch in Node 18+)
const response = await fetch('https://api.openai.com/v1/chat/completions', {
method: 'POST',
headers: {
'Authorization': 'Bearer ' + process.env.OPENAI_API_KEY,
'Content-Type': 'application/json'
},
body: JSON.stringify({
model: 'gpt-4',
messages: [
{ role: 'user', content: 'What is the capital of France?' }
]
})
});
const data = await response.json();
console.log(data.choices[0].message.content);
// Output: "The capital of France is Paris."
This pattern -- sending a POST request with a JSON body and parsing the JSON response -- is the foundation of every AI integration you will build.
Tools for Testing APIs
Before writing code, use these tools to test API calls:
- Postman: A desktop application for building and testing API requests without writing code
- Insomnia: Similar to Postman, open-source alternative
- curl: Command-line tool for making HTTP requests
- HTTPie: A more user-friendly command-line alternative to curl
Testing your API calls in Postman before writing code helps you understand the response structure and catch authentication issues early.
Practice Exercise
Using Postman or a similar tool:
- Create a new POST request to a public API (the JSONPlaceholder API at
https://jsonplaceholder.typicode.com/postsis free to use without authentication) - Send a request and examine the JSON response
- Identify the status code, the response body structure, and what data is returned
Key Takeaways
- An API (Application Programming Interface) is a defined way for one piece of software to communicate with another over a network.
- Every API interaction follows the request-response model: you send a request to an endpoint and receive a response.
- AI API calls are typically POST requests with a JSON body containing your prompt and model parameters.
- API keys are secret credentials that authenticate your requests -- never share or commit them publicly.
- JSON is the standard data format for API communication -- every AI engineer needs to be comfortable reading and parsing it.
Try it yourself
Key Takeaways
- An API (Application Programming Interface) is a defined contract for how software systems communicate with each other over a network.
- Every API interaction follows the request-response model: your code sends a request and receives a structured response.
- AI API calls are typically POST requests with JSON bodies containing your prompt, model choice, and parameters.
- API keys are secret credentials that authenticate your API requests -- store them in environment variables, never in code.
- JSON is the universal data format for API communication -- AI engineers must be fluent in reading and parsing JSON responses.
Quick Quiz
1.What does API stand for?
2.What HTTP method is almost always used when making AI API calls?
3.Why must API keys never be committed to a public code repository?
4.What does a 429 status code in an API response mean?
Ready to go further?
CareerEx gives you structured 12-week training, live classes every Saturday and Sunday, real tutor feedback, and a certificate. Join the next cohort.
Join CareerEx