Validating Response Bodies (URL-Encoded)

Avatar of Hemanta SundarayHemanta Sundaray

Some APIs return their response bodies as URL-encoded form data (application/x-www-form-urlencoded) instead of JSON. OAuth token endpoints are the most common example. Instead of returning {"access_token": "abc123", "token_type": "bearer"}, they return access_token=abc123&token_type=bearer&expires_in=3600.

HttpClientResponse.schemaBodyUrlParams validates these URL-encoded response bodies against a Schema, just like schemaBodyJson does for JSON responses.

http.ts
import { HttpClientResponse } from "effect/unstable/http";
import { Schema } from "effect";
const TokenResponse = Schema.Struct({
access_token: Schema.String,
token_type: Schema.String,
expires_in: Schema.NumberFromString,
});
// After executing a request to an OAuth token endpoint:
const token =
yield * HttpClientResponse.schemaBodyUrlParams(TokenResponse)(response);
// token is fully typed: { access_token: string, token_type: string, expires_in: number }
console.log(token.access_token);

schemaBodyUrlParams is curried, following the same pattern as schemaBodyJson:

Terminal
HttpClientResponse.schemaBodyUrlParams(TokenResponse)(response);
// ^^^^^^^^^^^^ ^^^^^^^^
// schema response

Under the hood, schemaBodyUrlParams() reads the response body as URL-encoded params, then validates the key-value pairs against your schema. If a declared field is missing or doesn’t match, you get a SchemaError.

Notice Schema.NumberFromString for expires_in. URL-encoded data is always strings, so the raw value is "3600". NumberFromString converts it to the number 3600 during validation.

Sign in to save progress

Stay in the loop

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