Skip to main content

The Fetch API

The fetch() API is the modern native JS method for making HTTP requests (GET, POST, PUT, DELETE) across web networks. It returns a Promise, solving the nightmare of old-school XMLHttpRequest objects.

Basic GET Request

To pull JSON data from a REST API using the highly clean async/await syntax:

async function getUser() {
try {
// 1. Await the initial network request
const response = await fetch("https://jsonplaceholder.typicode.com/users/1");

// Throw a manual error if the HTTP Status is bad (404, 500)
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}

// 2. Await the parsing of the data stream from raw bytes into JSON
const userData = await response.json();

console.log("Username: ", userData.username);
} catch (error) {
console.error("Network request failed!", error);
}
}

getUser();

Basic POST Request

When you want to send data (like a signup form) to a server:

async function createUser(newUser) {
try {
const response = await fetch("https://jsonplaceholder.typicode.com/users", {
method: "POST", // Specify HTTP method
headers: {
"Content-Type": "application/json" // Telling the server we are sending JSON
},
body: JSON.stringify(newUser) // Converting our JS Object into a JSON String
});

const confirmedUser = await response.json();
console.log("User successfully created in DB: ", confirmedUser);

} catch (error) {
console.error(error);
}
}

createUser({ name: "Midhun", email: "test@example.com" });