Home / Docs / Guides

HTTP

Release v0.4.0

The host capability Http sends HTTP/1.1 requests (spec/24, edition 0.2).

una
module weather

--- The temperature of a city, from a JSON API, or `None` when the request or its answer fails.
--- The token is the key `weather` of the run's `keys:` grant; the program never sees it.
pub temperature(city: Text) -> internal Option[internal Int]
  uses @http: Http[get]
=
  let accept = Header(name: "Accept", value: "application/json")
  let r = attempt @http.get("https://api.example.com/v1/now?city={city}", headers: [accept], key_name: Some("weather"))
  when r
    is Ok(response) -> if response.status == 200 then degrees(response.body) else None
    is Err(e) -> None

--- The `degrees` field of a JSON object, when it is an integer.
degrees(body: internal Text) -> internal Option[internal Int]
=
  let doc = body.parse_json()
    if error use Null
  when doc
    is Object(fields) ->
      let value = fields.get(key: "degrees")
        if none use Null
      when value
        is Number(n) -> Some(n)
        else -> None
    else -> None

A test of a function that uses Http installs a stand-in with given. Its parameter is named answer, not body, since an operation's parameter of the same name would clash with it (U1002):

una
module stand_in

--- The status of a GET, or `None` when the request gets no response.
pub status_of(url: Text) -> internal Option[internal Int]
  uses @http: Http[get]
=
  let r = attempt @http.get(url, headers: [], key_name: None)
  when r
    is Ok(response) -> Some(response.status)
    is Err(e) -> None

--- A stand-in for an API: every GET answers 200 with `answer`, and the other methods 405.
pub handler fixed_answer(answer: Text) for Http
  op get(url, headers, key_name) = Response(status: 200, headers: [], body: answer)
  op post(url, headers, body, key_name) = Response(status: 405, headers: [], body: "")
  op put(url, headers, body, key_name) = Response(status: 405, headers: [], body: "")
  op delete(url, headers, key_name) = Response(status: 405, headers: [], body: "")

example "the stand-in answers every GET"
  given @http = fixed_answer(answer: "ok")
  do status_of("https://api.example.com/v1/now")
  expect result == Some(200)