Posts Learn Components Snippets Categories Tags About
/

Send a POST Request with a Fetch API in JavaScript

Learn how to create a resource from the front-end with fetch to call an external API with the POST method.

Created on Aug 29, 2021

53 views

In this short snippet, you will learn how to create a resource from the front-end with the fetch API to call an external endpoint with the POST method.

Fetch with POST method


In this code example, we are calling a dummy API for testing. We will create a new "posts" resource that will have the following endpoint.
http://jsonplaceholder.typicode.com/posts
The code example will be as follows. It's very important to keep note that each of the code section is included. The 1st parameter is the URL to the resource, 2nd is an object that has the data for the request. In this case it will be the "method" to use, the request "body" and also "header",
fetch('https://jsonplaceholder.typicode.com/posts', {
  method: 'POST',
  body: JSON.stringify({
    title: 'foo',
    body: 'bar',
    userId: 1,
  }),
  headers: {
    'Content-type': 'application/json; charset=UTF-8',
  },
})
  .then((response) => response.json())
  .then((json) => console.log(json));

Code Output


Since by default the JSON placeholder API "posts" resource has 100 records, posting a new resource will create a post with id 101.
{
  id: 101,
  title: 'foo',
  body: 'bar',
  userId: 1
}
Important: resource will not be really updated on the server but it will be faked as if.

Snippets by

PostSrc poster

PostSrc

Full stack developer mainly focusing on the front end side of the web. The main author of PostSrc and loves writing tutorial and guides online.

new

PostSrc Code Components

Collection of Tailwind CSS components for everyone to use. Browse all of the components that's right for your project.

View Components

Other Code Snippets

More