JavaScript Fetch API: Make GET and POST Requests

Learn how to use the Fetch API with async/await, check HTTP errors, send JSON, and create a reusable request helper.

JavaScript Fetch API: Make GET and POST Requests

What is the Fetch API, and How do you use it?

When a web page needs data from a server, JavaScript can make an HTTP request. The Fetch API is a built-in API available in modern browsers for making those requests. It returns a Promise, so it works naturally with async/await.

The most important detail to remember is that fetch() usually does not reject just because the server returns an HTTP error such as 404 or 500. You need to check response.ok yourself before treating the response as a success.

Make a GET request

Here is a small browser example that requests JSON from a placeholder API:

async function loadPost() {
  try {
    const response = await fetch(
      "https://jsonplaceholder.typicode.com/posts/1",
    );

    if (!response.ok) {
      throw new Error(`Request failed: ${response.status}`);
    }

    const post = await response.json();
    console.log(post.title);
  } catch (error) {
    console.error("Could not load the post:", error);
  }
}

loadPost();

fetch() sends a GET request by default. It resolves to a Response object when a response arrives. response.json() reads and parses the response body, and it also returns a Promise, which is why we await that too.

The try...catch handles failures such as a network error, a rejected request, or an error we throw after checking response.ok. It will also catch a JSON parsing error. Decide at the appropriate layer whether to show a user-friendly message or pass the error to a caller.

Why check response.ok?

HTTP responses in the 400 and 500 ranges still produce a fulfilled Fetch Promise. For example, a missing page can return a valid HTTP response with status 404. fetch() does not consider that a network failure. The ok property is true for successful status codes (200–299) and false for other HTTP statuses.

const response = await fetch("/api/profile");

if (!response.ok) {
  throw new Error(`HTTP error: ${response.status}`);
}

const profile = await response.json();

Check before parsing as success. Some error responses have a JSON body that can help explain the failure; if your API provides one, you can parse that body in your error-handling path as well.

Send JSON with a POST request

To create or submit data, set the HTTP method, headers, and body. Convert a JavaScript object to JSON with JSON.stringify():

async function createPost() {
  const response = await fetch("https://jsonplaceholder.typicode.com/posts", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      title: "Learning Fetch",
      body: "A short example post",
      userId: 1,
    }),
  });

  if (!response.ok) {
    throw new Error(`Request failed: ${response.status}`);
  }

  return response.json();
}

The server must support the method and expect the body format you send. You can use other methods such as PUT, PATCH, and DELETE by setting method to the value your API expects. A GET request is the default.

Put repeated handling in a helper

In an application, several endpoints may need the same status check and JSON parsing. A small helper can keep that logic in one place:

async function fetchJson(url, options = {}) {
  const response = await fetch(url, options);

  if (!response.ok) {
    throw new Error(`HTTP ${response.status} for ${url}`);
  }

  return response.json();
}

const profile = await fetchJson("/api/profile");

You can extend a helper to set a base URL, add common headers, or handle authentication consistently. Keep API-specific behavior clear, and avoid putting secrets that belong on a server into browser code. For larger applications, a small API module can expose focused functions such as getProfile() or saveSettings() that call this helper.

A few details worth knowing

  • Fetch is available in modern browsers and also in current Node.js releases. A browser page calling a different origin may be subject to CORS rules; CORS is configured by the server, not bypassed by client code.
  • response.json() consumes the response body. In normal use, read a body only once. If you need to read the same response more than once, clone it before consuming it.
  • Fetch does not reject for ordinary HTTP error statuses, so check ok or status.
  • A request can take time or fail. In a UI, represent loading and error states so people know what is happening.

Try it yourself

Update the GET example to request a different post ID. Then change the URL to a path that returns a 404 and observe what your response.ok check does. Add a finally block if you want to reset a loading flag whether the request succeeds or fails.

Recap

  • fetch() makes an HTTP request and returns a Promise for a Response.
  • Use async/await to keep request code readable.
  • Check response.ok; HTTP 404 and 500 responses do not normally reject the Fetch Promise.
  • Parse JSON with await response.json() and send JSON with JSON.stringify().
  • Reusable helpers can centralize common headers, status checks, and parsing.

What's next?

Next, we’ll compare Local Storage, Session Storage, and Cookies, and discuss where an authentication token should be stored.

Written by

Dev Likhon

Dev Likhon

Full Stack Developer & Tech Educator

6+ years of professional development experience.

About Me
Share:

Comments

Share what you learned or ask a question.

Loading comments...