Using HttpClient

Avatar of Hemanta SundarayHemanta Sundaray

The most straightforward way to make a GET request is using the HttpClient service directly.

http.ts
import { FetchHttpClient, HttpClient } from "effect/unstable/http";
import { Effect } from "effect";
function fetchUser(userId: number) {
return Effect.gen(function* () {
// Step 1: Access the HttpClient service from the Effect context
const client = yield* HttpClient.HttpClient;
// Step 2: Make a GET request
const response = yield* client.get(`https://dummyjson.com/users/${userId}`);
// Step 3: Parse the response body as JSON
const user = yield* response.json;
return user;
}).pipe(
// Step 4: Provide the FetchHttpClient implementation
Effect.provide(FetchHttpClient.layer),
);
}
// Test it
Effect.runPromise(fetchUser(1)).then((user) => {
console.log("Name:", user.firstName, user.lastName);
});

Output:

Terminal
Name: Emily Johnson

We import two key modules:HttpClient and FetchHttpClient.

HttpClient is the main module for making HTTP requests. FetchHttpClient provides an HTTP client implementation using the browser/Node.js Fetch API.

Inside the fetchUser() function, we first access the HttpClient service from the Effect context using yield* HttpClient.HttpClient. Next, we call client.get(url) to make a GET request. We then parse the response body as JSON using response.json.

Finally, we pipe the result into Effect.provide(FetchHttpClient.layer) to provide the actual HTTP implementation to our program. Without it, the program wouldn’t know how to make real HTTP requests.

Sign in to save progress

Stay in the loop

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