Making POST Requests

Avatar of Hemanta SundarayHemanta Sundaray

A POST request tells the server to create a new resource. Unlike GET, which only retrieves data, POST sends data in the request body for the server to process.

http.ts
import {
FetchHttpClient,
HttpClient,
HttpClientRequest,
} from "effect/unstable/http";
import { Effect } from "effect";
function addPost(post: { title: string; body: string; userId: number }) {
return Effect.gen(function* () {
const client = yield* HttpClient.HttpClient;
const request = HttpClientRequest.post(
"https://dummyjson.com/posts/add",
).pipe(HttpClientRequest.bodyJsonUnsafe(post));
const response = yield* client.execute(request);
const data = yield* response.json;
return data;
}).pipe(Effect.provide(FetchHttpClient.layer));
}
// Test it
Effect.runPromise(
addPost({
title: "Effect is awesome",
body: "A deep dive into the Effect HTTP client module.",
userId: 1,
}),
).then((data) => {
console.log("Created post:", data);
});

Output:

Terminal
Created post: {
id: 252,
title: 'Effect is awesome',
body: 'A deep dive into the Effect HTTP client module.',
userId: 1
}

HttpClientRequest.post(url) creates a request with the POST method. Unlike GET requests, POST requests carry data in the request body. This data can be in different formats: JSON, plain text, FormData, or a file stream.

In the example above, we’re sending JSON using bodyJsonUnsafe, which takes a plain JavaScript object and serializes it as JSON, setting the Content-Type header automatically. HttpClient actually provides three methods for sending JSON data: bodyJson, bodyJsonUnsafe, and schemaBodyJson. Each offers a different level of type safety. These are covered in detail in the Sending JSON Data chapter.

For sending other body types, the Sending Files and Sending Form Data chapters cover their respective APIs.

Note that the dummyJSON API simulates creation. It returns the submitted data with a new id, but doesn’t actually store it on the server.

Sign in to save progress

Stay in the loop

Get notified when new chapters are added and when this course is complete.