This site counts visits with analytics cookies only if you accept. Read the consent

Skip to content

ExamplesEncoding

Encoding

Custom body and search params encoding with default values.

Source Configuration

Configure encoding options on the defineApi call. These apply to all endpoints in the source.

ts
import { defineApi } from "@noverax/courier/define"

const encodedApi = defineApi({
  baseURL: "http://localhost:4000",
  groups: { echo },

  // Sends URL-encoded body instead of JSON
  bodySerializer: (data) =>
    new URLSearchParams(
      Object.entries(data).map(([k, v]) => [k, String(v)])
    ),

  // Encodes arrays as key[]=val1&key[]=val2
  searchParamsSerializer: {
    stringify: (params) => {
      const sp = new URLSearchParams()
      for (const [key, value] of Object.entries(params)) {
        if (Array.isArray(value)) {
          for (const item of value)
            sp.append(`${key}[]`, String(item))
        } else {
          sp.append(key, String(value))
        }
      }
      return sp.toString()
    },
    parse: (str) =>
      Object.fromEntries(new URLSearchParams(str).entries()),
  },

  // Merged into every call's variables: a write's body, a read's query
  defaultBody: { apiVersion: "v2" },
  // Merged into every call's query string, a write's too
  defaultQueryParams: { format: "json" },
})

The source above configures custom body encoding, search params encoding, and default values. See the demos below for interactive examples.

Encoding docs

Body Encoding

Compare JSON (default) vs URL-encoded body. Both send the same data to the echo endpoint, which answers with the type and the bytes it was sent: rawBody.

run the call
ts
// Default (api): JSON body
await caller.echo.send({ name: "John", role: "admin" })
// POST /echo
// Content-Type: application/json
// Body: {"name":"John","role":"admin"}

// Custom (encodedApi): URL-encoded body + defaultBody merged
await encodedCaller.echo.send({ name: "John", role: "admin" })
// POST /echo?format=json
// Content-Type: application/x-www-form-urlencoded;charset=UTF-8
// Body: apiVersion=v2&name=John&role=admin
echo.send — two body encodingsSANDBOX

JSON body

idle
// run the request to see the response

URL-encoded body

idle
// run the request to see the response

Requests

as the browser recorded them and the site's server told of them

// no request yet: run the call

Search Params Encoding

Custom encoder supports arrays. Arrays are encoded as key[]=val1&key[]=val2.

ts
// Custom searchParamsSerializer supports arrays
await encodedCaller.echo.retrieve({
  tags: ["javascript", "react"],
  page: 1,
})
// GET /echo?format=json&apiVersion=v2&tags%5B%5D=javascript&tags%5B%5D=react&page=1
// — tags[]=javascript&tags[]=react, its brackets encoded
echo.retrieve — arrays in the querySANDBOX
idle
// run the request to see the response

Requests

as the browser recorded them and the site's server told of them

// no request yet: run the call

Default Data & Query Params

defaultBody merges into a write's body and a read's query, as a read's variables go; defaultQueryParams into every call's query string. The requests below show each address the site's server asked the API for, and the echo answers with the bytes it got.

ts
// A write: defaultBody in its body, defaultQueryParams in its query
await encodedCaller.echo.send({ name: "John" })
// POST /echo?format=json
// Body: apiVersion=v2&name=John

// A read: both in its query, as a read's variables are
await encodedCaller.echo.retrieve({ page: 1 })
// GET /echo?format=json&apiVersion=v2&page=1
echo — defaultBody · defaultQueryParamsSANDBOX

POST body, with apiVersion added

idle
// run the request to see the response

GET query, with format added

idle
// run the request to see the response

Requests

as the browser recorded them and the site's server told of them

// no request yet: run the call