JSON
Web Development
API Integration
HTTP Methods
Programming

Fetch, POST JSON data

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

The Fetch API in JavaScript is a powerful tool for making network requests, similar to XMLHttpRequest. It is more powerful and flexible, as it handles requests asynchronously using Promises, making it a better choice for modern web development. One of the common uses of the Fetch API is to send (POST) JSON data to a server. This is typically done when you need to submit data from a form or control a web application.

Understanding the Fetch API

The Fetch API provides a JavaScript interface for accessing and manipulating parts of the HTTP pipeline, such as requests and responses. It not only allows you to request resources but also to send data to a server in various formats including JSON, which is a common format for encoding data in web applications.

How to POST JSON Data Using Fetch

To send JSON data using the Fetch API, you need to create an HTTP POST request, and include the JSON data in the body of the request. Here is a step-by-step guide on how to do it:

1. Create JSON data

First, you need to create the JSON object that you will send to the server. This is generally derived from form inputs or dynamic data within your application.

javascript
1const data = {
2    name: "John Doe",
3    email: "[email protected]"
4};

2. Use Fetch to send the request

Use the fetch() function to send a POST request. You need to specify the URL of the API endpoint, and also provide a configuration object which includes the method, headers, and the body.

javascript
1fetch('https://api.example.com/data', {
2    method: 'POST', // or 'PUT'
3    headers: {
4        'Content-Type': 'application/json',
5    },
6    body: JSON.stringify(data) // convert JavaScript object to JSON string
7})
8.then(response => response.json()) // or .text() if not JSON
9.then(json => console.log('Success:', json))
10.catch(err => console.error('Error:', err));

Detailed Breakdown of Fetch Options

  • URL: The first parameter of fetch() is the URL to which the request is sent.
  • Method: The HTTP method, e.g., POST, GET, PUT, DELETE, etc.
  • Headers: Set of request headers. Content-Type: application/json is necessary to let the server know that the request body format is JSON.
  • Body: Data to be sent to the server. It must be a string, so if you are sending JSON data, use JSON.stringify() to convert the object into a JSON string.

Error Handling

Handling errors with Fetch correctly is crucial for building reliable applications:

javascript
1fetch('https://api.example.com/data', {
2    method: 'POST',
3    headers: {
4        'Content-Type': 'application/json',
5    },
6    body: JSON.stringify(data)
7})
8.then(response => {
9    if (!response.ok) {
10        throw new Error('Network response was not ok ' + response.status);
11    }
12    return response.json();
13})
14.then(json => console.log('Success:', json))
15.catch(err => console.error('Error:', err));

In this example, it checks whether response.ok is true, which is a shorthand for status range 200-299, indicating that the HTTP status code was successful.

Summary Table

FeatureFunctionality
URLSpecifies the endpoint URL.
MethodHTTP method used (e.g., POST, GET).
HeadersRequest headers (e.g., Content-Type: application/json).
BodyData sent to server, as a JSON string.
Error HandlingHandling fetch and server errors properly.
Response ConversionConverting the raw response into JSON or text format.

Conclusion

Using the Fetch API to post JSON data is a robust method for modern web development, facilitating server communication in a promise-based manner. By understanding and properly utilising this API, developers can integrate sophisticated functionalities into their web applications efficiently.


Related reading
Course
Beginner
27 lessons
10 hours
System Design Fundamentals

Build a strong foundation in designing scalable, reliable distributed systems.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

All Rights Reserved.