Home / Snippets / Send a POST Request with a Fetch API in JavaScript
Send a POST Request with a Fetch API in JavaScript cover

Send a POST Request with a Fetch API in JavaScript


2 years ago


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.
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.
notion avatar


Week-end developer currently experimenting with web, mobile, and all things programming.






Support Us

If you like our tutorial, support us by being our Patreon or buy us some coffee ☕️

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this