cashmere

cashmere

Gleam httpc

My personal example

pub fn request() -> Result(Nil, httpc.HttpError) {
  let assert Ok(base_request) = request.to("hello") // set the url
  let req =
    base_request
    |> request.set_method(http.Post) // set method
    // |> request.set_body() // set the body if needed (embed a json input)
    |> request.prepend_header("content-type", "application/json")
    |> request.prepend_header("accept", "application/json")

  use resp <- result.try(httpc.send(req))
  Ok(Nil)
}

Example of the library

import gleam/http/request
import gleam/http/response
import gleam/httpc
import gleam/result
import gleeunit/should

pub fn send_request() {
  // Prepare a HTTP request record
  let assert Ok(base_req) =
    request.to("https://test-api.service.hmrc.gov.uk/hello/world")

  let req =
    request.prepend_header(base_req, "accept", "application/vnd.hmrc.1.0+json")

  // Send the HTTP request to the server
  use resp <- result.try(httpc.send(req))

  // We get a response record back
  resp.status
  |> should.equal(200)

  resp
  |> response.get_header("content-type")
  |> should.equal(Ok("application/json"))

  resp.body
  |> should.equal("{\"message\":\"Hello World\"}")

  Ok(resp)
}