Using bodyJson

Avatar of Hemanta SundarayHemanta Sundaray

HttpClientRequest.bodyJson() does the same thing as bodyJsonUnsafe. It serializes your data to JSON, but it wraps the result in an Effect. This means serialization failures are captured as a typed HttpBodyError in the error channel.

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;
// bodyJson returns Effect<HttpClientRequest, HttpBodyError>
// so we need yield* to unwrap it
const request = yield* HttpClientRequest.post(
"https://dummyjson.com/posts/add",
).pipe(HttpClientRequest.bodyJson(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
}

Because bodyJson returns an Effect<HttpClientRequest, HttpBodyError> instead of a plain HttpClientRequest, we need yield* to unwrap it before passing it to client.execute().

Use bodyJson when you’re dealing with data whose shape you don’t fully control. User input, data from external sources, or any situation where you want maximum safety.

Sign in to save progress

Stay in the loop

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