Home > Software engineering >  How do you make an HTTP request with Gleam?
How do you make an HTTP request with Gleam?

Time:03-08

I'm trying out the gleam programming language and I was hoping to do some simple things to get a feel for the language. One thing I wanted to try out was making HTTP request and I've gotten as far as:

import gleam/io
import gleam/http/request
import gleam/uri.{parse}

pub fn main() {
  try uri = parse("https://lichess.org/api/puzzle/daily")
  let req = request.from_uri(uri)

  io.debug(req)
}

Which if I run outputs

{ok,{request,get,[],<<>>,https,<<"lichess.org">>,none,<<"/api/puzzle/daily">>,
             none}}

This makes me think that the Request object is correctly being constructed, but I'm not seeing any requests being made. How do I fire off this request?

CodePudding user response:

I've discovered over the course of writing out this question that the gleam/http library does not actually provide an HTTP client, which is what I was looking for. Likewise, it doesn't provide an HTTP server, however, all of the examples in the documentation for gleam/http show how to go about setting up a server with either gleam/cowboy or gleam/elli which made their relationship to the core gleam/http library clear to me.

The correct approach was to use an HTTP client library, for example gleam/hackney

I ended up with the following code:

import gleam/io
import gleam/hackney
import gleam/http/request
import gleam/uri.{parse}

pub fn main() {
  try uri = parse("https://lichess.org/api/puzzle/daily")
  try req = request.from_uri(uri)
  let resp = hackney.send(req)
  case resp {
    Ok(r) -> io.println(r.body)
    Error(_e) -> io.println("Failed")
  }
  Ok(Nil)
}

Which correctly performs the request and prints the body

  •  Tags:  
  • http
  • Related