Setting Accept Header

Avatar of Hemanta SundarayHemanta Sundaray

A common header you’ll set on almost every API call is Accept, which tells the server what content type you expect in the response.

HttpClientRequest provides a shorthand for this:

http.ts
import {
FetchHttpClient,
HttpClient,
HttpClientRequest,
} from "effect/unstable/http";
import { Effect } from "effect";
function fetchProducts() {
return Effect.gen(function* () {
const client = yield* HttpClient.HttpClient;
const request = HttpClientRequest.get(
"https://dummyjson.com/products",
).pipe(
HttpClientRequest.setUrlParam("limit", "3"),
HttpClientRequest.accept("application/json"),
);
const response = yield* client.execute(request);
const data = yield* response.json;
return data;
}).pipe(Effect.provide(FetchHttpClient.layer));
}
// Test it
Effect.runPromise(fetchProducts()).then((data) => {
data.products.forEach((product) => {
console.log(` - ${product.title}: $${product.price}`);
});
});

Output:

Terminal
- Essence Mascara Lash Princess: $9.99
- Eyeshadow Palette with Mirror: $19.99
- Powder Canister: $14.99

.accept("application/json") is equivalent to setHeader("accept", "application/json"), just shorter and more expressive.

For the very common case of requesting JSON, there’s an even shorter version: HttpClientRequest.acceptJson.

const request = HttpClientRequest.get("https://dummyjson.com/products").pipe(
HttpClientRequest.acceptJson,
);

acceptJson is not a function call. It’s a pre-built transform. You pass it directly to .pipe() without parentheses.

Sign in to save progress

Stay in the loop

Get notified when new Effect Atom related content is published.