Getting started

Sooner or later your Gleam program needs something that lives behind another service’s HTTP API: a price, a user record, a token, an answer from a model. You want to ask for it, get a typed value back, know clearly when it didn’t work, and test all of that without the real service. This guide takes you from an empty project to exactly that: a small module that calls an API, decodes its JSON, reports each kind of failure, and has tests that run against a local server.

Table of Contents

What you’ll build

In this guide you’ll:

Before you start

Make a project with gleam new greeter and go into its folder. Then add the client. The examples decode JSON with gleam_json, so add that too:

gleam add dream_http_client gleam_json

You don’t start or configure anything before the first request. The client runs as an OTP application, and Gleam starts it with your program.

Every example talks to dream_mock_server on localhost:9876, so you can run them exactly as they’re written. This guide uses two of its endpoints: /text answers Hello, World! as plain text, and /json answers {"message":"Hello, World!","success":true}. The Test your code section shows how to add the mock server as a dev dependency and start it from a test. You can also run it on its own: clone its repository and run make run, which listens on port 3004, so change the port in the examples to match.

Which function to call

The client has one way to build a request and four ways to send it. Pick by what you do with the answer:

Your situationUseWhy
You need the whole answer before you can use it: a JSON API, a small filesendIt returns the status, the headers and the complete body in one Result. This guide uses it.
The body is large, slow or endless, and you handle it piece by piecestream_yielder or start_streamYou get each chunk as it arrives. See Streaming a response.
An OTP actor must get the stream as messages, next to its other messagesstream_toSee Streaming into an OTP actor.

All four take the same request, so everything in this guide about building a request applies to them too.

Step 1: Send your first request

Here’s a complete program. It builds a request for http://localhost:9876/text, sends it, and prints what came back:

Send a request and print the answer Tested snippet

import dream_http_client/client.{
  type HttpResponse, host, path, port, scheme, send,
}
import gleam/http
import gleam/int
import gleam/io
import gleam/result
import gleam/string

pub fn main() -> Nil {
  let request =
    client.new()
    |> scheme(http.Http)
    |> host("localhost")
    |> port(9876)
    |> path("/text")

  case send(request) {
    Ok(response) -> print_response(response)
    Error(error) -> io.println("The request failed: " <> string.inspect(error))
  }
}

fn print_response(response: HttpResponse) -> Nil {
  let text = client.body_text(response) |> result.unwrap("<not text>")
  io.println("Status: " <> int.to_string(response.status))
  io.println("Body: " <> text)
}

Run it with gleam run, and it prints:

What main prints Tested snippet

Status: 200
Body: Hello, World!

Here’s what happens:

Step 2: Wrap the API in a module of your own

Printing a body is fine for a first try. In a real program you don’t want HTTP details in every function that needs a greeting. You want one module that knows how to talk to the API and gives the rest of the program a Gleam value.

Here’s that module. It knows where the API lives, sends the request, and decodes the JSON into a Greeting:

Fetch a greeting and decode its JSON Tested snippet

import dream_http_client/client.{
  type ClientRequest, type TransportError, RequestError, ResponseError, path,
  send,
}
import gleam/dynamic/decode
import gleam/http
import gleam/int
import gleam/json
import gleam/result

pub type Greeting {
  Greeting(message: String, success: Bool)
}

pub type ApiError {
  /// The request did not get an answer: no connection, a timeout, a
  /// connection that closed.
  Unreachable(error: TransportError)
  /// The server answered with a status of 400 or more.
  BadStatus(status: Int)
  /// The server answered 2xx, but the body is not the JSON we expect.
  BadBody(error: json.DecodeError)
}

/// The base request of the API: its scheme, host and port. Every endpoint
/// function starts from it, so one place says where the API lives.
pub fn local_api() -> ClientRequest {
  client.new()
  |> client.scheme(http.Http)
  |> client.host("localhost")
  |> client.port(9876)
}

pub fn fetch_greeting(api: ClientRequest) -> Result(Greeting, ApiError) {
  use response <- result.try(
    api
    |> path("/json")
    |> send()
    |> result.map_error(to_api_error),
  )
  json.parse_bits(response.body, greeting_decoder())
  |> result.map_error(BadBody)
}

fn to_api_error(error: client.SendError) -> ApiError {
  case error {
    ResponseError(response: response) -> BadStatus(status: response.status)
    RequestError(error: transport_error) -> Unreachable(error: transport_error)
  }
}

fn greeting_decoder() -> decode.Decoder(Greeting) {
  use message <- decode.field("message", decode.string)
  use success <- decode.field("success", decode.bool)
  decode.success(Greeting(message: message, success: success))
}

fetch_greeting(local_api()) returns:

The greeting Tested snippet

Ok(Greeting("Hello, World!", True))

A few choices in this module are worth copying:

Step 3: Tell the failures apart

Each case of ApiError asks for a different reaction from your program, so it pays to keep them apart. Here’s what fetch_greeting returns in each situation:

What fetch_greeting returns in each case Tested snippet

the API answers its greeting       -> Ok(Greeting("Hello, World!", True))
nothing listens on the port        -> Error(Unreachable(ConnectFailed("Connection refused")))
the API answers 503                -> Error(BadStatus(503))
the API answers <html></html>      -> Error(BadBody(UnexpectedByte("0x3C")))

To show an error to a person or write it to a log, add one function to the module that turns it into a message:

Describe an API error Tested snippet

/// A message about the error, for a log or for the person who waits.
pub fn describe_api_error(error: ApiError) -> String {
  case error {
    Unreachable(error: transport_error) ->
      "Cannot reach the API: "
      <> client.transport_error_to_string(transport_error)
    BadStatus(status: status) -> "The API answered " <> int.to_string(status)
    BadBody(error: _) -> "The API sent a body that is not a greeting"
  }
}

For the unreachable case it returns Cannot reach the API: Connection failed: Connection refused, and for the 503 it returns The API answered 503. client.transport_error_to_string writes the part about the transport error, so you don’t have to match each variant just to log it.

One thing the client does for you: when a connection closes before the server answers, it sends a GET once more on a new connection, because a GET is safe to repeat. It doesn’t do that for a POST. The Handling errors, timeouts and retries guide has the full rule.

Step 4: Call it from your program

Your main, or a request handler, or an actor, now calls one function and handles one error type:

Print the greeting or the error Tested snippet

import gleam/io
import snippets/guide_getting_started_api_client.{
  describe_api_error, fetch_greeting, local_api,
}

pub fn main() -> Nil {
  case fetch_greeting(local_api()) {
    Ok(greeting) -> io.println(greeting.message)
    Error(error) -> io.println_error(describe_api_error(error))
  }
}

With the mock server running, it prints Hello, World!. When the call fails, it prints the message of describe_api_error to standard error instead, for example Cannot reach the API: Connection failed: Connection refused.

In a real program, local_api() is where the API’s address comes from. Read the host from an environment variable or your config there, and the rest of the program never needs to know.

Test your code

Because fetch_greeting takes the base request as a parameter, you can point it at any server. dream_mock_server gives you two kinds:

Add the test dependencies first, under [dev-dependencies] in your gleam.toml. These are the lines of this package’s own gleam.toml:

The test dependencies Tested snippet

dream_mock_server = ">= 2.0.0 and < 3.0.0"
dream_test = ">= 3.0.0 and < 4.0.0"

Here’s a test module for fetch_greeting with one test for the greeting and one for each failure that a server can cause. It uses dream_test:

Test fetch_greeting against mock servers Tested snippet

import dream_http_client/client.{port}
import dream_mock_server/config.{Exact, MockRoute}
import dream_mock_server/server
import dream_test/matchers.{be_equal, or_fail_with, should}
import dream_test/suite.{type TestSuite}
import dream_test/unit.{describe, it}
import gleam/json
import gleam/option.{None}
import snippets/guide_getting_started_api_client.{
  BadBody, BadStatus, Greeting, fetch_greeting, local_api,
}

pub fn tests() -> TestSuite {
  describe("fetch_greeting", [
    it("decodes the greeting of the API", fn() {
      // Arrange
      let assert Ok(mock) = server.start(19_971)

      // Act
      let greeting = fetch_greeting(local_api() |> port(19_971))
      server.stop(mock)

      // Assert
      greeting
      |> should
      |> be_equal(Ok(Greeting(message: "Hello, World!", success: True)))
      |> or_fail_with("Expected the greeting of the mock server")
    }),
    it("reports the status of an API that is down", fn() {
      // Arrange
      let routes = [MockRoute("/json", Exact, None, 503, "Down for repairs")]
      let assert Ok(mock) = server.start_with_config(19_972, routes)

      // Act
      let greeting = fetch_greeting(local_api() |> port(19_972))
      server.stop(mock)

      // Assert
      greeting
      |> should
      |> be_equal(Error(BadStatus(status: 503)))
      |> or_fail_with("Expected BadStatus(503)")
    }),
    it("reports a body that is not JSON", fn() {
      // Arrange
      let routes = [MockRoute("/json", Exact, None, 200, "<html></html>")]
      let assert Ok(mock) = server.start_with_config(19_973, routes)

      // Act
      let greeting = fetch_greeting(local_api() |> port(19_973))
      server.stop(mock)

      // Assert
      greeting
      |> should
      |> be_equal(Error(BadBody(error: json.UnexpectedByte("0x3C"))))
      |> or_fail_with("Expected BadBody for an HTML body")
    }),
  ])
}

Each test starts its own server on its own port and stops it again, so the tests can run at the same time without getting in each other’s way. The unreachable case needs no server at all: a base request with port(1) is enough, as Step 3 showed.

Common pitfalls

Leaving out the scheme. Symptom: Error(RequestError(ConnectFailed(reason: "closed"))) from a server you know is running. Fix: client.new() defaults to HTTPS, and a plain HTTP server closes the connection when the TLS handshake starts. Add scheme(http.Http) for a plain HTTP server.

Putting the URL in host. Symptom: Error(RequestError(ConnectFailed(reason: "DNS resolution failed (NXDOMAIN)"))). Fix: host takes only the host name, such as "localhost" or "api.example.com". Set the scheme, port and path with their own functions.

Forgetting the port. Symptom: Error(RequestError(ConnectFailed(reason: "Connection refused"))) when the server runs on a port like 9876. Fix: without port(), the client uses 80 for HTTP and 443 for HTTPS. Set the port when the server uses another one.

Treating every Ok as success. Symptom: your code tries to decode a redirect page. Fix: send() returns Ok for every status below 400, which includes 3xx when you turn off redirects. The client follows redirects by default, so you only see a 3xx when you ask for it. Check response.status when it matters to you.

Where to go next

✨ Search Document