Setting a Specific `Content-Type` for a Single Endpoint in Effect Typescript

Effect Tip: Setting Content-Type on a Single Endpoint


Hey everyone!

Ever needed a specific Content-Type for just one endpoint in your
HttpApi
, while the rest of the API group uses a default? You can attach encoding metadata directly to your request Schema.

The key is HttpApiSchema.withEncoding.

Example:

Let's say your /search endpoint requires a specific application/json header.

import * as S from '@effect/schema/Schema'
import { HttpApiEndpoint, HttpApiGroup, HttpApiSchema } from '@effect/platform'

// Define your request schema as usual
export const SearchPostRequest = S.Struct({
    collections: S.optional(S.Array(S.String)),
    // ... other fields
})
.pipe(
    // V-- Attach encoding metadata directly to the schema
    HttpApiSchema.withEncoding({
        kind: 'Json',
        contentType: 'application/json',
    }),
)
.annotations({ identifier: 'SearchPostRequest' })

export type SearchPostRequest = typeof SearchPostRequest.Type

// Your endpoint definition doesn't need to change
export const ApiGroupSearch = HttpApiGroup.make('Search').add(
    HttpApiEndpoint.post('post', '/search')
        .setPayload(SearchPostRequest)
        .addSuccess(/* ... */),
)


Now,
HttpApi
will automatically set the Content-Type: application/json header whenever this SearchPostRequest schema is used as a payload, without affecting any other endpoints.
Was this page helpful?