API Fundamentals: Beginner Guide
Table of Contents
1. What is an API?
2. Types of APIs
3. HTTP Fundamentals
4. REST API Basics
5. API Request Structure
6. API Response Structure
7. Status Codes
8. Basic Authentication
9. Common API Operations
10. Your First API Call
What is an API?
Definition
API (Application Programming Interface) is a set of rules and protocols that allows different software
applications to communicate with each other. It's like a contract that defines how software components
should interact.
Real-World Analogy
Think of an API like a restaurant:
Menu (API Documentation): Shows what's available and how to order
Customer (Client Application): Makes requests for food
Waiter (API): Takes your order and brings back food
Kitchen (Server/Database): Prepares the food based on the order
Why APIs Exist
1. Data Sharing: Allow applications to share information
2. Functionality Access: Use features from other applications
3. System Integration: Connect different software systems
4. Code Reusability: Avoid rebuilding existing functionality
5. Scalability: Distribute workload across multiple services
Key Components
Client: The application making the request
Server: The application providing the service
Request: What the client asks for
Response: What the server sends back
Endpoint: Specific URL where API can be accessed
Types of APIs
1. Web APIs (Most Common)
APIs that operate over the internet using HTTP protocol.
Examples:
Weather API: Get current weather data
Payment API: Process online payments
Social Media API: Post to Twitter, Facebook
Maps API: Get location and direction data
2. Library APIs
Functions and methods provided by programming libraries.
Examples:
python
# Python library API
import requests
response = requests.get('https://api.example.com/data')
import math
result = math.sqrt(16) # Using math library API
3. Operating System APIs
Allow applications to interact with the operating system.
Examples:
File system operations
Network operations
Hardware access
Process management
4. Database APIs
Enable applications to interact with databases.
Examples:
SQL APIs
NoSQL APIs
ORM (Object-Relational Mapping) APIs
5. Hardware APIs
Allow software to control hardware components.
Examples:
Camera APIs
Sensor APIs
Bluetooth APIs
GPS APIs
HTTP Fundamentals
What is HTTP?
HTTP (HyperText Transfer Protocol) is the foundation of data communication on the web. Most web
APIs use HTTP to send and receive data.
HTTP Request Structure
GET /api/users/123 HTTP/1.1
Host: api.example.com
Authorization: Bearer token123
Content-Type: application/json
HTTP Response Structure
HTTP/1.1 200 OK
Content-Type: application/json
Content-Length: 85
{
"id": 123,
"name": "John Doe",
"email": "[email protected]"
}
HTTP Methods (Verbs)
1. GET: Retrieve data from server
2. POST: Send data to server (create new resource)
3. PUT: Update existing resource completely
4. PATCH: Update part of existing resource
5. DELETE: Remove resource from server
6. HEAD: Get headers only (no body)
7. OPTIONS: Get allowed methods for endpoint
HTTP Headers
Headers provide metadata about the request/response:
Common Request Headers:
Content-Type : Format of data being sent
Authorization : Authentication credentials
Accept : Formats client can handle
User-Agent : Information about client application
Common Response Headers:
Content-Type : Format of returned data
Content-Length : Size of response body
Cache-Control : Caching instructions
Server : Information about server
REST API Basics
What is REST?
REST (Representational State Transfer) is an architectural style for designing web APIs. It's the most
popular approach for building web APIs.
REST Principles
1. Stateless: Each request contains all information needed
2. Client-Server: Clear separation of concerns
3. Cacheable: Responses can be cached to improve performance
4. Uniform Interface: Consistent way to interact with resources
5. Layered System: Architecture can have multiple layers
Resources and URIs
In REST, everything is a resource identified by a URI (Uniform Resource Identifier).
Examples:
GET /api/users # Get all users
GET /api/users/123 # Get user with ID 123
POST /api/users # Create new user
PUT /api/users/123 # Update user 123
DELETE /api/users/123 # Delete user 123
RESTful URL Design
Good Examples:
GET /api/users # Get all users
GET /api/users/123 # Get specific user
GET /api/users/123/orders # Get orders for user 123
POST /api/users # Create new user
PUT /api/users/123 # Update user 123
DELETE /api/users/123 # Delete user 123
Bad Examples:
GET /api/getUsers # Don't use verbs in URLs
GET /api/user_123 # Use consistent naming
POST /api/users/123/delete # Use HTTP methods, not URLs
API Request Structure
URL Components
https://api.example.com:443/v1/users/123?include=orders&sort=name#section
│ │ │ │ │ │ │
│ │ │ │ │ │ └─ Fragment
│ │ │ │ │ └─ Query Parameters
│ │ │ │ └─ Resource Path
│ │ │ └─ API Version
│ │ └─ Port
│ └─ Domain/Host
└─ Protocol
Query Parameters
Used to filter, sort, or modify requests:
GET /api/users?page=2&limit=10&sort=name&filter=active
Common Query Parameters:
page : Pagination page number
limit : Number of items per page
sort : Sort order
filter : Filter criteria
include : Related data to include
fields : Specific fields to return
Request Body
Data sent with POST, PUT, PATCH requests:
json
{
"name": "John Doe",
"email": "[email protected]",
"age": 30,
"address": {
"street": "123 Main St",
"city": "New York",
"country": "USA"
}
}
Content Types
application/json : JSON data (most common)
application/xml : XML data
application/x-www-form-urlencoded : Form data
multipart/form-data : File uploads
text/plain : Plain text
API Response Structure
JSON Response Format
Most APIs return data in JSON format:
json
{
"status": "success",
"data": {
"id": 123,
"name": "John Doe",
"email": "[email protected]",
"created_at": "2024-01-15T10:30:00Z"
},
"message": "User retrieved successfully"
}
Common Response Patterns
Single Resource:
json
{
"id": 123,
"name": "John Doe",
"email": "[email protected]"
}
Collection of Resources:
json
{
"data": [
{
"id": 123,
"name": "John Doe"
},
{
"id": 124,
"name": "Jane Smith"
}
],
"meta": {
"total": 150,
"page": 1,
"per_page": 10
}
}
Error Response:
json
{
"error": {
"code": "VALIDATION_ERROR",
"message": "Invalid email format",
"details": {
"field": "email",
"value": "invalid-email"
}
}
}
Status Codes
HTTP Status Code Categories
1xx: Informational (rare in APIs)
2xx: Success
3xx: Redirection
4xx: Client Error
5xx: Server Error
Common Success Codes (2xx)
200 OK: Request succeeded
201 Created: Resource created successfully
202 Accepted: Request accepted for processing
204 No Content: Success but no content to return
Common Client Error Codes (4xx)
400 Bad Request: Invalid request syntax
401 Unauthorized: Authentication required
403 Forbidden: Access denied
404 Not Found: Resource doesn't exist
405 Method Not Allowed: HTTP method not supported
409 Conflict: Resource conflict
422 Unprocessable Entity: Validation errors
429 Too Many Requests: Rate limit exceeded
Common Server Error Codes (5xx)
500 Internal Server Error: Generic server error
502 Bad Gateway: Invalid response from upstream
503 Service Unavailable: Service temporarily unavailable
504 Gateway Timeout: Upstream server timeout
Basic Authentication
What is Authentication?
Authentication verifies the identity of the client making the API request.
1. API Keys
Simple authentication method using a unique key:
GET /api/users
Authorization: Bearer your-api-key-here
Or as query parameter:
GET /api/users?api_key=your-api-key-here
2. Basic Authentication
Uses username and password encoded in Base64:
GET /api/users
Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=
3. Bearer Tokens
Uses tokens (often JWT) for authentication:
GET /api/users
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
4. API Key in Headers
Custom header for API key:
GET /api/users
X-API-Key: your-api-key-here
Common API Operations
CRUD Operations
Most APIs support CRUD (Create, Read, Update, Delete) operations:
Create (POST)
POST /api/users
Content-Type: application/json
{
"name": "John Doe",
"email": "[email protected]"
}
Read (GET)
GET /api/users/123
Update (PUT/PATCH)
PUT /api/users/123
Content-Type: application/json
{
"name": "John Smith",
"email": "[email protected]"
}
Delete (DELETE)
DELETE /api/users/123
Pagination
Handle large datasets by breaking them into pages:
GET /api/users?page=1&limit=10
Response:
json
{
"data": [...],
"pagination": {
"current_page": 1,
"per_page": 10,
"total": 150,
"total_pages": 15,
"next_page": 2,
"prev_page": null
}
}
Filtering and Sorting
GET /api/users?filter=active&sort=name&order=asc
Searching
GET /api/users?search=john&fields=name,email
Your First API Call
Using cURL (Command Line)
bash
# GET request
curl https://api.github.com/users/octocat
# POST request
curl -X POST https://api.example.com/users \
-H "Content-Type: application/json" \
-d '{"name": "John Doe", "email": "[email protected]"}'
# With authentication
curl -H "Authorization: Bearer your-token" \
https://api.example.com/users/me
Using Python
python
import requests
# GET request
response = requests.get('https://api.github.com/users/octocat')
if response.status_code == 200:
user_data = response.json()
print(user_data['name'])
else:
print(f"Error: {response.status_code}")
# POST request
user_data = {
"name": "John Doe",
"email": "[email protected]"
}
response = requests.post(
'https://api.example.com/users',
json=user_data,
headers={'Authorization': 'Bearer your-token'}
)
Using JavaScript
javascript
// GET request
fetch('https://api.github.com/users/octocat')
.then(response => response.json())
.then(data => console.log(data.name))
.catch(error => console.error('Error:', error));
// POST request
const userData = {
name: "John Doe",
email: "[email protected]"
};
fetch('https://api.example.com/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer your-token'
},
body: JSON.stringify(userData)
})
.then(response => response.json())
.then(data => console.log(data));
Next Steps
Once you understand these fundamentals, you'll be ready to:
1. Learn about advanced authentication methods
2. Understand API versioning and documentation
3. Implement error handling and retry logic
4. Build your own APIs
5. Work with real-time APIs (WebSockets, Server-Sent Events)
6. Implement caching and rate limiting
7. Handle file uploads and downloads
8. Work with GraphQL APIs
This foundation will prepare you for the intermediate and advanced concepts covered in the next
documents!