scream/fetch
Download pages and feeds politely.
A Fetcher waits before every request, sends the User-Agent you give it,
follows redirects, and when a server answers 429 (Too Many Requests) or
503 it waits as long as the server asked (Retry-After) or backs off
exponentially, then tries again.
import scream
import scream/fetch
let fetcher = fetch.new("my-research-bot/1.0 (+https://example.com/bot)")
let assert Ok(response) =
fetch.get(fetcher, "https://www.reddit.com/r/GovernmentContracting/new/.rss")
let assert Ok(feed) = scream.parse_xml(response.body)
For a JSON API, add fetch.with_header("accept", "application/json") and
decode response.body with gleam_json.
Use a User-Agent that says who you are and how to reach you: sites rate limit and block anonymous clients first.
Types
Why no response came back.
pub type FetchError {
InvalidUrl(url: String)
ConnectionFailed(reason: String)
Timeout
NotText
}
Constructors
-
InvalidUrl(url: String)The URL couldn’t be read.
-
ConnectionFailed(reason: String)The server couldn’t be reached, after every retry.
-
TimeoutNo response arrived within the timeout, after every retry.
-
NotTextThe body wasn’t UTF-8 text.
How to make requests: who to say you are, which headers to send, and how long to wait.
pub opaque type Fetcher
A server’s answer. Every status is returned as Ok, including 404 and a
429 that outlasted the retries, so check status yourself: some sites
send a useful body with an error status.
url is the URL you asked for; redirects are followed but not recorded.
pub type Response {
Response(
url: String,
status: Int,
headers: List(#(String, String)),
body: String,
)
}
Constructors
-
Response( url: String, status: Int, headers: List(#(String, String)), body: String, )
Values
pub fn get(
fetcher: Fetcher,
url: String,
) -> Result(Response, FetchError)
GET a URL, waiting and retrying as the fetcher is set up to.
pub fn new(user_agent: String) -> Fetcher
A fetcher that sends user_agent with every request.
Defaults: 2 seconds between requests, 3 retries, a 30 second timeout, and at most 60 seconds of waiting before a retry.
pub fn with_delay(fetcher: Fetcher, milliseconds: Int) -> Fetcher
Milliseconds to wait before every request. This is also the first backoff step when retrying.
pub fn with_header(
fetcher: Fetcher,
name: String,
value: String,
) -> Fetcher
Send an extra header with every request, such as accept or
authorization.
pub fn with_max_wait(
fetcher: Fetcher,
milliseconds: Int,
) -> Fetcher
The longest wait before a retry, in milliseconds. If a server’s
Retry-After asks for longer, the fetcher stops and returns that response
instead of sleeping.
pub fn with_retries(fetcher: Fetcher, retries: Int) -> Fetcher
How many times to retry after a 429, a 503, a timeout or a failed connection.