Skip to content

HTTP ​

The Http module follows Elm: a request is a value, and sending it produces a Cmd whose messages carry either the decoded result or a typed error.

Everything on this page runs against JSONPlaceholder, a free public test API. Nothing below is a stand-in.

Install ​

Http needs no extra package: it uses the HTTP client that ships inside effect.

No client configuration is needed - Http.send and Http.toTask provide Effect's FetchHttpClient themselves.

Describing the data ​

Start with a schema. It is not documentation: it is the thing that decides whether a response is allowed into your model.

ts
// A JSONPlaceholder user carries more than this - address, phone, company.
// Schema.Struct ignores fields you do not list, so the model stays as small as
// the application actually needs.
export const User = Schema.Struct({
  id: Schema.Number,
  name: Schema.String,
  username: Schema.String,
  email: Schema.String
})

export type User = Schema.Schema.Type<typeof User>

export const NewUser = Schema.Struct({
  name: Schema.String,
  username: Schema.String,
  email: Schema.String
})

export type NewUser = Schema.Schema.Type<typeof NewUser>

A JSONPlaceholder user carries more fields than these - address, phone, company, website. Schema.Struct ignores what you do not list, so your model stays as small as the feature needs.

Describing the request ​

ts
// JSONPlaceholder is a free public test API. These requests run as they are -
// nothing below is a stand-in for a real endpoint.
const BASE_URL = 'https://jsonplaceholder.typicode.com'

// A request is a value. Building one sends nothing.
export const listUsers = pipe(
  Http.get(`${BASE_URL}/users`, Http.expectJson(Schema.Array(User))),
  Http.withTimeout(5000)
)

// JSONPlaceholder replies with the object you sent plus an id, but does not
// store it: the next listUsers still returns the original ten users.
export const createUser = (user: NewUser) =>
  Http.post(`${BASE_URL}/users`, Http.jsonBody(NewUser, user), Http.expectJson(User))

Note what has not happened: no request has been sent. listUsers is a value you can pass around, store in a module, or hand to Http.send twice.

Headers ​

Modifiers are ordinary Request -> Request functions, so a combination you use everywhere can be named once:

ts
// JSONPlaceholder needs no authentication. This is the shape for an API that does.
// Modifiers are ordinary Request -> Request functions, so a combination you use
// everywhere can be named once and then piped in like any other modifier.
export const authorized = (token: string) => Http.withHeaders([Http.bearerToken(token)])

export const createUserAs = (token: string, user: NewUser) =>
  pipe(createUser(user), authorized(token))

For Authorization and Content-Type there are helpers - bearerToken, authorization, contentType. Reach for withHeader when the library has none.

The complete file, imports included
ts
import { Schema, pipe } from 'effect'
import * as Http from 'tea-effect/Http'

// #region schema
// A JSONPlaceholder user carries more than this - address, phone, company.
// Schema.Struct ignores fields you do not list, so the model stays as small as
// the application actually needs.
export const User = Schema.Struct({
  id: Schema.Number,
  name: Schema.String,
  username: Schema.String,
  email: Schema.String
})

export type User = Schema.Schema.Type<typeof User>

export const NewUser = Schema.Struct({
  name: Schema.String,
  username: Schema.String,
  email: Schema.String
})

export type NewUser = Schema.Schema.Type<typeof NewUser>
// #endregion schema

// #region requests
// JSONPlaceholder is a free public test API. These requests run as they are -
// nothing below is a stand-in for a real endpoint.
const BASE_URL = 'https://jsonplaceholder.typicode.com'

// A request is a value. Building one sends nothing.
export const listUsers = pipe(
  Http.get(`${BASE_URL}/users`, Http.expectJson(Schema.Array(User))),
  Http.withTimeout(5000)
)

// JSONPlaceholder replies with the object you sent plus an id, but does not
// store it: the next listUsers still returns the original ten users.
export const createUser = (user: NewUser) =>
  Http.post(`${BASE_URL}/users`, Http.jsonBody(NewUser, user), Http.expectJson(User))
// #endregion requests

// #region posts
export const Post = Schema.Struct({
  id: Schema.Number,
  userId: Schema.Number,
  title: Schema.String
})

export type Post = Schema.Schema.Type<typeof Post>

export const postsOf = (userId: number) =>
  Http.get(`${BASE_URL}/posts?userId=${userId}`, Http.expectJson(Schema.Array(Post)))
// #endregion posts

// #region headers
// JSONPlaceholder needs no authentication. This is the shape for an API that does.
// Modifiers are ordinary Request -> Request functions, so a combination you use
// everywhere can be named once and then piped in like any other modifier.
export const authorized = (token: string) => Http.withHeaders([Http.bearerToken(token)])

export const createUserAs = (token: string, user: NewUser) =>
  pipe(createUser(user), authorized(token))
// #endregion headers

// #region download
// JSONPlaceholder sends no Content-Disposition, so the file is named after the
// last URL segment: this saves the user list as a file called `users`.
export const usersFile = Http.get(`${BASE_URL}/users`, Http.expectFile)
// #endregion download

// #region upload
// JSONPlaceholder accepts the upload and answers with an id, but keeps nothing.
export const Created = Schema.Struct({ id: Schema.Number })

// The whole body is the file: the server reads it as it is.
export const uploadCsv = (csv: File) => Http.post(`${BASE_URL}/posts`, Http.fileBody(csv), Http.expectJson(Created))

// A form: fields and files together, as multipart/form-data.
export const uploadAvatar = (photo: File) =>
  Http.post(
    `${BASE_URL}/posts`,
    Http.multipartBody([Http.stringPart('userId', '1'), Http.filePart('avatar', photo)]),
    Http.expectJson(Created)
  )
// #endregion upload

Sending it ​

Http.send takes the request and a message for each outcome:

tsx
// Message constructors, so the handlers below read as names rather than literals.
const UsersReceived = (users: ReadonlyArray<User>): Msg => ({ type: 'UsersReceived', users })
const RequestFailed = (error: Http.HttpError): Msg => ({ type: 'RequestFailed', error })

export const update = (msg: Msg, model: Model): readonly [Model, Cmd.Cmd<Msg>] => {
  switch (msg.type) {
    case 'LoadRequested':
      // Already in flight - ignore. The model makes this check obvious.
      if (model._tag === 'Loading') {
        return [model, Cmd.none]
      }
      return [
        { _tag: 'Loading' },
        // Both outcomes become messages, so this Cmd cannot fail: its `E` is `never`.
        Http.send(listUsers, { onSuccess: UsersReceived, onError: RequestFailed })
      ]

    case 'UsersReceived':
      return [{ _tag: 'Loaded', users: msg.users }, Cmd.none]

    case 'RequestFailed':
      return [{ _tag: 'Failed', error: msg.error }, Cmd.none]
  }
}

The resulting Cmd<Msg, never, never> cannot fail. Its error type is never because both outcomes were turned into messages - which is the rule from the mental model: an HTTP 404 is not a program crash, it is a fact your update handles.

The model that goes with it ​

Because failure is an ordinary message, the model can name every state exactly once:

tsx
export type Model =
  | { readonly _tag: 'Idle' }
  | { readonly _tag: 'Loading' }
  | { readonly _tag: 'Loaded'; readonly users: ReadonlyArray<User> }
  | { readonly _tag: 'Failed'; readonly error: Http.HttpError }

Four states, no impossible combinations. Loading cannot carry an error; Failed cannot also hold users.

Handling errors ​

HttpError is a closed union of six cases, and the compiler makes you cover all of them:

tsx
// Every branch is required: `HttpError` is a closed union, so adding a case to it
// is a compile error here rather than a silently unhandled failure.
export const describeError = (error: Http.HttpError): string => {
  switch (error._tag) {
    case 'BadUrl':
      return `Invalid URL: ${error.url}`

    case 'Timeout':
      return 'The request timed out'

    case 'NetworkError':
      return 'Network error - check your connection'

    case 'BadStatus':
      return `The server responded with ${error.status}`

    case 'BadBody':
      // The response arrived but did not match the schema.
      return 'The server sent data we could not read'

    case 'BadRequestBody':
      // Encoding failed, so no request was ever sent.
      return 'We could not encode the request'
  }
}

The two that get confused:

BadBodyThe response arrived, but it did not match your schema.
BadRequestBodyEncoding your payload failed, so no request was ever sent.
The complete file, imports included
tsx
import * as Cmd from 'tea-effect/Cmd'
import * as Http from 'tea-effect/Http'
import type * as TeaReact from 'tea-effect/React'
import { listUsers, type User } from './api'

// #region model
export type Model =
  | { readonly _tag: 'Idle' }
  | { readonly _tag: 'Loading' }
  | { readonly _tag: 'Loaded'; readonly users: ReadonlyArray<User> }
  | { readonly _tag: 'Failed'; readonly error: Http.HttpError }
// #endregion model

export type Msg =
  | { readonly type: 'LoadRequested' }
  | { readonly type: 'UsersReceived'; readonly users: ReadonlyArray<User> }
  | { readonly type: 'RequestFailed'; readonly error: Http.HttpError }

export const init: readonly [Model, Cmd.Cmd<Msg>] = [{ _tag: 'Idle' }, Cmd.none]

// #region update
// Message constructors, so the handlers below read as names rather than literals.
const UsersReceived = (users: ReadonlyArray<User>): Msg => ({ type: 'UsersReceived', users })
const RequestFailed = (error: Http.HttpError): Msg => ({ type: 'RequestFailed', error })

export const update = (msg: Msg, model: Model): readonly [Model, Cmd.Cmd<Msg>] => {
  switch (msg.type) {
    case 'LoadRequested':
      // Already in flight - ignore. The model makes this check obvious.
      if (model._tag === 'Loading') {
        return [model, Cmd.none]
      }
      return [
        { _tag: 'Loading' },
        // Both outcomes become messages, so this Cmd cannot fail: its `E` is `never`.
        Http.send(listUsers, { onSuccess: UsersReceived, onError: RequestFailed })
      ]

    case 'UsersReceived':
      return [{ _tag: 'Loaded', users: msg.users }, Cmd.none]

    case 'RequestFailed':
      return [{ _tag: 'Failed', error: msg.error }, Cmd.none]
  }
}
// #endregion update

// #region errors
// Every branch is required: `HttpError` is a closed union, so adding a case to it
// is a compile error here rather than a silently unhandled failure.
export const describeError = (error: Http.HttpError): string => {
  switch (error._tag) {
    case 'BadUrl':
      return `Invalid URL: ${error.url}`

    case 'Timeout':
      return 'The request timed out'

    case 'NetworkError':
      return 'Network error - check your connection'

    case 'BadStatus':
      return `The server responded with ${error.status}`

    case 'BadBody':
      // The response arrived but did not match the schema.
      return 'The server sent data we could not read'

    case 'BadRequestBody':
      // Encoding failed, so no request was ever sent.
      return 'We could not encode the request'
  }
}
// #endregion errors

export const view =
  (model: Model): TeaReact.Html<Msg> =>
  (dispatch) => {
    switch (model._tag) {
      case 'Idle':
        return <button onClick={() => dispatch({ type: 'LoadRequested' })}>Load users</button>

      case 'Loading':
        return <p>Loading...</p>

      case 'Loaded':
        return (
          <ul>
            {model.users.map((user) => (
              <li key={user.id}>{user.name}</li>
            ))}
          </ul>
        )

      case 'Failed':
        return (
          <div>
            <p>{describeError(model.error)}</p>
            <button onClick={() => dispatch({ type: 'LoadRequested' })}>Try again</button>
          </div>
        )
    }
  }

Answers that arrive out of order ​

LoadRequested above ignores a second click while the list loads, and that is enough when the request cannot change. When it can - a search as the user types, a list that follows a filter or a selection, a refresh - a new request can go out before the last one answers, and answers need not arrive in the order the requests went out. update cannot tell a late answer to an old request from the answer to the current one, so whichever arrives last wins.

Put the command under a key with Cmd.latest:

ts
const PostsReceived = (posts: ReadonlyArray<Post>): Msg => ({ type: 'PostsReceived', posts })
const PostsFailed = (error: Http.HttpError): Msg => ({ type: 'PostsFailed', error })

// Every load fills the same list, so every load runs under the same key: a newer
// load aborts the one still running, and its answer never reaches `update`.
const loadPosts = (userId: number): Cmd.Cmd<Msg> =>
  pipe(Http.send(postsOf(userId), { onSuccess: PostsReceived, onError: PostsFailed }), Cmd.latest('posts'))

export const update = (msg: Msg, model: Model): readonly [Model, Cmd.Cmd<Msg>] => {
  switch (msg.type) {
    case 'UserSelected':
      // The user can pick another user before the posts of the last one arrive.
      return [{ userId: msg.userId, posts: { _tag: 'Loading' } }, loadPosts(msg.userId)]

    case 'PostsReceived':
      // Always the posts of `model.userId`: an answer to an earlier pick was dropped.
      return [{ ...model, posts: { _tag: 'Loaded', posts: msg.posts } }, Cmd.none]

    case 'PostsFailed':
      return [{ ...model, posts: { _tag: 'Failed', error: msg.error } }, Cmd.none]
  }
}

When a command under a key starts, the runtime interrupts the one already running under that key - its fetch is aborted - and drops every message of the earlier command that update has not received yet, including one already waiting its turn. update sees only the answer to the latest request, with no request id in the model and no check in its branches.

What keeps it right:

  • Reads only. A newer command cancels the earlier one, so a save never goes under a key.
  • One key per place the answer goes, not per request: 'posts' for the list above. A module shown in several places at once takes its key from its parent, since two places under one key would cancel each other.
  • Cmd.map and Cmd.batch keep the key, and in one batch the last command with a key wins. A Stream operator applied by hand gives back a command without the key, which runs like any other.
  • Cmd.latest(key)(Cmd.none) stops whatever runs under the key, for an answer that is no longer wanted.

Outside a program - running the command as a Stream in a test - nothing is replaced, and every message arrives.

The complete file, imports included
ts
import { pipe } from 'effect'
import * as Cmd from 'tea-effect/Cmd'
import * as Http from 'tea-effect/Http'
import { postsOf, type Post } from './api'

export type Model = {
  readonly userId: number
  readonly posts:
    | { readonly _tag: 'Loading' }
    | { readonly _tag: 'Loaded'; readonly posts: ReadonlyArray<Post> }
    | { readonly _tag: 'Failed'; readonly error: Http.HttpError }
}

export type Msg =
  | { readonly type: 'UserSelected'; readonly userId: number }
  | { readonly type: 'PostsReceived'; readonly posts: ReadonlyArray<Post> }
  | { readonly type: 'PostsFailed'; readonly error: Http.HttpError }

// #region latest
const PostsReceived = (posts: ReadonlyArray<Post>): Msg => ({ type: 'PostsReceived', posts })
const PostsFailed = (error: Http.HttpError): Msg => ({ type: 'PostsFailed', error })

// Every load fills the same list, so every load runs under the same key: a newer
// load aborts the one still running, and its answer never reaches `update`.
const loadPosts = (userId: number): Cmd.Cmd<Msg> =>
  pipe(Http.send(postsOf(userId), { onSuccess: PostsReceived, onError: PostsFailed }), Cmd.latest('posts'))

export const update = (msg: Msg, model: Model): readonly [Model, Cmd.Cmd<Msg>] => {
  switch (msg.type) {
    case 'UserSelected':
      // The user can pick another user before the posts of the last one arrive.
      return [{ userId: msg.userId, posts: { _tag: 'Loading' } }, loadPosts(msg.userId)]

    case 'PostsReceived':
      // Always the posts of `model.userId`: an answer to an earlier pick was dropped.
      return [{ ...model, posts: { _tag: 'Loaded', posts: msg.posts } }, Cmd.none]

    case 'PostsFailed':
      return [{ ...model, posts: { _tag: 'Failed', error: msg.error } }, Cmd.none]
  }
}
// #endregion latest

export const init: readonly [Model, Cmd.Cmd<Msg>] = [{ userId: 1, posts: { _tag: 'Loading' } }, loadPosts(1)]

Downloading a file ​

A file is a response like any other. Describe it with Http.expectFile and the body arrives as a File:

ts
// JSONPlaceholder sends no Content-Disposition, so the file is named after the
// last URL segment: this saves the user list as a file called `users`.
export const usersFile = Http.get(`${BASE_URL}/users`, Http.expectFile)

The name comes from Content-Disposition - filename* first, so a UTF-8 name survives, then filename - and, without that header, from the last segment of the URL. The type is the response's Content-Type.

To save it, hand the request to File.Download.send. The command fetches the file and saves it the way a download link would; update hears only its name:

ts
const Exported = (name: string): Msg => ({ type: 'Exported', name })
const ExportFailed = (error: Http.HttpError): Msg => ({ type: 'ExportFailed', error })

export const update = (msg: Msg, model: Model): readonly [Model, Cmd.Cmd<Msg>] => {
  switch (msg.type) {
    case 'ExportRequested':
      // A second click while the first export runs would save the file twice.
      if (model.exporting) {
        return [model, Cmd.none]
      }
      // The Cmd fetches the file and saves it; only its name comes back.
      return [
        { ...model, exporting: true, error: null },
        File.Download.send(usersFile, { onSuccess: Exported, onError: ExportFailed })
      ]
    case 'Exported':
      return [{ exporting: false, saved: msg.name, error: null }, Cmd.none]
    case 'ExportFailed':
      return [{ ...model, exporting: false, error: msg.error }, Cmd.none]
  }
}

The file never passes through a message, so the model and the message history stay small and serialisable. A failed request saves nothing and ends in onError with an ordinary HttpError, so a server can answer a failed export with the same JSON errors as any other route.

Uploading a file ​

A file goes to the server as the body of the request - the whole body, or one part of a multipart/form-data form:

ts
// JSONPlaceholder accepts the upload and answers with an id, but keeps nothing.
export const Created = Schema.Struct({ id: Schema.Number })

// The whole body is the file: the server reads it as it is.
export const uploadCsv = (csv: File) => Http.post(`${BASE_URL}/posts`, Http.fileBody(csv), Http.expectJson(Created))

// A form: fields and files together, as multipart/form-data.
export const uploadAvatar = (photo: File) =>
  Http.post(
    `${BASE_URL}/posts`,
    Http.multipartBody([Http.stringPart('userId', '1'), Http.filePart('avatar', photo)]),
    Http.expectJson(Created)
  )

Http.fileBody sends the file from disk with the file's own Content-Type. Http.multipartBody takes stringPart, filePart and bytesPart; the browser writes its Content-Type, boundary included, so do not set that header yourself. For content the application built, Http.stringBody and Http.bytesBody take the MIME type explicitly.

Files from the user, and to the user ​

The rest of File works the same way, after Elm's elm/file. File.Download.text and File.Download.bytes save content the application built itself, and File.Download.url lets the browser download a URL straight to disk. In the other direction, File.Select.file and File.Select.files ask the user for files, and File.toText, File.toBytes and File.toDataUrl read them.

Choosing an entry point ​

Provides the clientUse it for
Http.send(req, handlers)Yes, FetchHttpClientNormal application code
Http.sendRaw(req, handlers)No - leaves HttpClient in RTests with a stub client
Http.toTask(req)YesComposing with other Effects before it becomes a Cmd
Http.toTaskRaw(req)NoThe same, under test

sendBy(onSuccess, onError)(req) is send with the arguments the other way round, for pipelines.

Next ​

  • Dependency injection - putting the API behind a service so the feature does not know about HTTP at all.
  • Testing - running this command against a stub.

Released under the MIT License.