š
Introduction to APIs
Beginner
100 XP
30 min
Lesson Content
Introduction to APIs
An API (Application Programming Interface) is a set of rules and protocols that allows different software applications to communicate with each other.
What is an API?
- Interface - Contract between applications
- Communication - How systems exchange data
- Standardization - Common format for requests/responses
Types of APIs
- REST - Representational State Transfer (most common)
- GraphQL - Query language for APIs
- SOAP - Simple Object Access Protocol
- WebSocket - Real-time bidirectional communication
API Components
- Endpoint - URL where API is accessed
- Method - HTTP method (GET, POST, PUT, DELETE)
- Request - Data sent to API
- Response - Data returned from API
Example API Call
// GET request
fetch('https://api.example.com/users')
.then(response => response.json())
.then(data => console.log(data));
// POST request
fetch('https://api.example.com/users', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: 'John', email: 'john@example.com' })
});Example Code
Practice making GET and POST requests
// Simulate API calls
// GET request function
function getUsers() {
// Simulate API response
return Promise.resolve([
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' }
]);
}
// POST request function
function createUser(userData) {
// Simulate API response
return Promise.resolve({ id: 3, ...userData });
}
// Use the functions
async function main() {
// Your code here
}
main();Expected Output:
Users: [{id: 1, name: 'Alice'}, {id: 2, name: 'Bob'}]
Created user: {id: 3, name: 'Charlie', email: 'charlie@example.com'}Study Tips
- ā¢Read the theory content thoroughly before practicing
- ā¢Review the example code to understand key concepts
- ā¢Proceed to the Practice tab when you're ready to code