Working with APIs in JavaScript (GET & POST)
APIs (Application Programming Interfaces) allow JavaScript applications to communicate with external services to fetch or send data. The most common HTTP methods are:
- GET: Retrieve data
- POST: Send data
What You Need:
- A public API (we'll use JSONPlaceholder)
- JavaScript (in browser or Node.js environment)
- fetch() method or async/await syntax
1. GET Request – Fetch Data from an API
Example Using .then():
fetch("https://jsonplaceholder.typicode.com/posts/1")
.then(response => response.json())
.then(data => {
console.log("Title:", data.title);
})
.catch(error => {
console.error("Error fetching data:", error);
});
Example Using async/await:
async function getPost() {
try {
const response = await
fetch("https://jsonplaceholder.typicode.com/posts/1");
const data = await response.json();
console.log("Title:", data.title);
} catch (err) {
console.error("GET Error:", err.message);
}
}
getPost();
2. POST Request – Send Data to an API
Example Using .then():
fetch("https://jsonplaceholder.typicode.com/posts", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
title: "Hello API",
body: "This is a POST request.",
userId: 101
})
})
.then(response => response.json())
.then(data => {
console.log("POST Response:", data);
})
.catch(error => {
console.error("POST Error:", error);
});
Example Using async/await:
async function createPost() {
try {
const response = await
fetch("https://jsonplaceholder.typicode.com/posts", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
title: "New Post",
body: "Learning APIs with JavaScript",
userId: 202
})
});
const data = await response.json();
console.log("New Post Created:", data);
} catch (err) {
console.error("POST Error:", err.message);
}
}
createPost();
Pro Tip: Always check for response status
if (!response.ok) {
throw new Error("HTTP error! Status: " + response.status);
}
Real-World Use Cases:
- GET user profiles, weather data, or news feeds
- POST contact form data or user comments
- Build SPAs that rely on REST APIs
- Integrate with services like Firebase, Stripe, or Google APIs