Skip to main content

Command Palette

Search for a command to run...

HTTP Methods & Sending Data With Fetch API

Updated
6 min readView as Markdown

Yesterday, I learned how to use the Fetch API to retrieve data from external servers using GET requests.

Today, I explored how applications can also send, update, and delete data using different HTTP methods.

I learned about:

  • GET

  • POST

  • PUT

  • PATCH

  • DELETE

I also learned how to send JSON data using fetch().

This takes me one step closer to understanding how frontend applications communicate with backend APIs.

Let's dive in.


What are HTTP Methods?

HTTP methods tell a server what action we want to perform.

The most common methods are:

Method Purpose
GET Retrieve data
POST Create new data
PUT Replace existing data
PATCH Partially update data
DELETE Delete data

These methods form the foundation of communication between frontend applications and APIs.


GET Request

A GET request is used to retrieve data.

Yesterday, I used:

fetch("https://jsonplaceholder.typicode.com/users")

This asks the server to return user data.

A simple GET request:

const response = await fetch(
    "https://jsonplaceholder.typicode.com/users"
);

const users = await response.json();

console.log(users);

POST Request

A POST request is generally used to create new data.

For example, creating a new user.

const response = await fetch(
    "https://jsonplaceholder.typicode.com/users",
    {
        method: "POST"
    }
);

But the server also needs to know what data we're sending.


Sending JSON Data

We can send data using the body property.

const user = {
    name: "Saurabh",
    email: "saurabh@example.com",
    role: "Developer"
};

const response = await fetch(
    "https://jsonplaceholder.typicode.com/users",
    {
        method: "POST",

        headers: {
            "Content-Type": "application/json"
        },

        body: JSON.stringify(user)
    }
);

Here:

method

method: "POST"

Tells the server that we're creating/sending data.

headers

"Content-Type": "application/json"

Tells the server that the request body contains JSON.

body

body: JSON.stringify(user)

Converts our JavaScript object into a JSON string.


Reading the POST Response

The server may send a response after creating the data.

const data = await response.json();

console.log(data);

The response can contain information about the newly created resource.


PUT Request

PUT is generally used to replace an existing resource.

For example:

const updatedUser = {
    name: "Saurabh",
    email: "new@example.com",
    role: "Full Stack Developer"
};

const response = await fetch(
    "https://jsonplaceholder.typicode.com/users/1",
    {
        method: "PUT",

        headers: {
            "Content-Type": "application/json"
        },

        body: JSON.stringify(updatedUser)
    }
);

With PUT, we're generally providing the complete representation of the resource we want to replace.


PATCH Request

PATCH is generally used for a partial update.

Suppose we only want to change the user's role.

const response = await fetch(
    "https://jsonplaceholder.typicode.com/users/1",
    {
        method: "PATCH",

        headers: {
            "Content-Type": "application/json"
        },

        body: JSON.stringify({
            role: "Full Stack Developer"
        })
    }
);

Unlike PUT, we don't necessarily need to send the entire resource.


PUT vs PATCH

PUT PATCH
Generally replaces the resource Generally partially updates it
Usually sends the complete representation Usually sends only changed fields
Used for full updates Used for partial updates

Understanding this distinction becomes important when working with REST APIs.


DELETE Request

The DELETE method is used to remove a resource.

const response = await fetch(
    "https://jsonplaceholder.typicode.com/users/1",
    {
        method: "DELETE"
    }
);

The server decides whether the resource is actually deleted based on its own implementation.


Checking the Response

Just like with GET, we should check whether the request succeeded.

if (!response.ok) {
    throw new Error("Request failed");
}

Example:

async function createUser() {

    try {

        const response = await fetch(
            "https://jsonplaceholder.typicode.com/users",
            {
                method: "POST",

                headers: {
                    "Content-Type": "application/json"
                },

                body: JSON.stringify({
                    name: "Saurabh",
                    email: "saurabh@example.com"
                })
            }
        );

        if (!response.ok) {
            throw new Error("Failed to create user");
        }

        const data = await response.json();

        console.log(data);

    } catch (error) {

        console.error(error);

    }
}

This pattern is useful when working with APIs.


Sending Form Data to an API

The concepts from Day 42 can now connect with today's topic.

Suppose we have a form:

<form id="userForm">

    <input
        id="name"
        name="name"
        placeholder="Name"
    >

    <input
        id="email"
        name="email"
        placeholder="Email"
    >

    <button type="submit">
        Create User
    </button>

</form>

We can capture the form and send the data to an API.

const form = document.querySelector("#userForm");

form.addEventListener("submit", async function (event) {

    event.preventDefault();

    const user = {
        name: document.querySelector("#name").value,
        email: document.querySelector("#email").value
    };

    const response = await fetch(
        "https://jsonplaceholder.typicode.com/users",
        {
            method: "POST",

            headers: {
                "Content-Type": "application/json"
            },

            body: JSON.stringify(user)
        }
    );

    const data = await response.json();

    console.log(data);

});

Now the workflow becomes:

Form → JavaScript → JSON → API → Response

This is much closer to how real applications work.


REST API CRUD

The four fundamental data operations are often represented as CRUD:

CRUD HTTP Method Operation
Create POST Create data
Read GET Retrieve data
Update PUT / PATCH Update data
Delete DELETE Delete data

CRUD operations appear in almost every application that manages data.

For example:

Create User   → POST
View Users    → GET
Edit User     → PATCH
Delete User   → DELETE

API Request Flow

The complete process now looks like:

User
 ↓
Frontend
 ↓
JavaScript
 ↓
HTTP Request
 ↓
API / Server
 ↓
Database
 ↓
API Response
 ↓
JavaScript
 ↓
DOM
 ↓
User

Understanding this flow is extremely important for becoming a full-stack developer.


Best Practices

✔ Use the correct HTTP method for the operation.

✔ Set Content-Type: application/json when sending JSON.

✔ Use JSON.stringify() for JSON request bodies.

✔ Check response.ok before assuming a request succeeded.

✔ Handle network and server errors with try...catch.

✔ Validate user input before sending it to the server.

✔ Never expose private API keys or secrets in frontend code.


My Biggest Takeaway

Today, I learned that APIs aren't only about getting data.

Applications also need to create, update, and delete information.

Understanding POST, PUT, PATCH, and DELETE helped me see how frontend applications communicate with backend systems to perform CRUD operations.

The workflow is becoming much clearer:

User Input → JavaScript → JSON → HTTP Request → Server → Response → DOM

2 views

100 Days of Code: My Journey to Becoming a Full Stack Developer

Part 46 of 50

Welcome to my 100 Days of Code journey! In this series, I'll document my daily progress as I learn Full Stack Web Development from the ground up. Every post will cover what I learned, challenges I faced, mistakes I made, and the projects I built. My goal is not just to complete 100 days but to become a better developer through consistency, discipline, and learning in public. Topics I'll cover include: • Git & GitHub • HTML, CSS & JavaScript • React.js • Node.js & Express • MongoDB • APIs • Real-world Projects • AI tools for Developers Whether you're just starting out or revising your fundamentals, I hope this journey helps you learn alongside me. Let's build, learn, and grow together! 🚀

Up next

HTTP Status Codes & Headers – Understanding API Communication

Over the past few days, I've learned how JavaScript communicates with APIs using the Fetch API. Today, I went deeper into what actually comes back from an HTTP request. I explored HTTP status codes, r

More from this blog

T

TheSaurceCode

73 posts

Documenting my journey to becoming a Full Stack Developer through daily blogs, coding challenges, projects, tutorials, and lessons learned. Learn, build, and grow with me