APIs (Application Programming Interfaces) are the bridges that allow your JavaScript code to interact with external services, databases, or other applications. In web development, they enable dynamic content loading without full page reloads—think fetching user data, posting forms, or displaying real-time updates.
An API is a set of rules and protocols that allows different software components to communicate. In JavaScript, we often deal with RESTful APIs (Representational State Transfer), which use standard HTTP methods to perform CRUD operations (Create, Read, Update, Delete) on resources.
APIs typically expose endpoints (URLs) like https://api.example.com/users. You send HTTP requests to these endpoints and receive responses, usually in JSON format.
fetch('https://api.example.com/endpoint')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
Below is an interactive example using the Dog CEO API to fetch random dog images. This demonstrates asynchronous JavaScript with Promises and Fetch.
JSON (JavaScript Object Notation) is a lightweight data-interchange format that's easy for humans to read and machines to parse. It's the de facto standard for API responses in JavaScript.
JSON uses key-value pairs, similar to JavaScript objects, but with stricter rules: double quotes for strings, no trailing commas, no functions.
{
"name": "John Doe",
"age": 30,
"hobbies": ["reading", "coding"],
"address": {
"street": "123 Main St",
"city": "Anytown"
}
}
Suppose an API returns user data:
{
"userId": 1,
"id": 1,
"title": "delectus aut autem",
"completed": false
}
In JavaScript, you can parse it with response.json() and access like data.title.
JSON.stringify(obj) converts a JavaScript object to a JSON string (for sending data via POST). JSON.parse(str) does the reverse.
const user = { name: 'Alice', age: 25 };
const jsonString = JSON.stringify(user);
console.log(jsonString); // '{"name":"Alice","age":25}'
const parsed = JSON.parse(jsonString);
console.log(parsed.name); // 'Alice'
APIs use HTTP methods to define actions. These are the building blocks of CRUD operations.
Used to fetch resources. Idempotent (safe to repeat). No body in request.
fetch('https://jsonplaceholder.typicode.com/posts/1')
.then(response => response.json())
.then(data => console.log(data));
Sends data to create a new resource. Includes a request body (usually JSON).
fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ title: 'New Post', body: 'Content', userId: 1 })
})
.then(response => response.json())
.then(data => console.log(data));
Deletes a resource. Idempotent.
fetch('https://jsonplaceholder.typicode.com/posts/1', { method: 'DELETE' })
.then(response => console.log('Deleted:', response.ok));
Pro Tip: Always handle errors with .catch() or try-catch in async/await. Check response status with response.ok.