### Configure HTTP Client Options in Gleam Source: https://context7.com/gleam-lang/httpc/llms.txt Illustrates how to combine all available configuration options for the Gleam HTTP client using a builder pattern. This example demonstrates enabling TLS verification, following redirects, setting a timeout, and dispatching a request. ```gleam import gleam/http/request import gleam/httpc pub fn full_configuration() { let assert Ok(req) = request.to("https://api.example.com/data") let result = httpc.configure() |> httpc.verify_tls(True) // Enable TLS verification |> httpc.follow_redirects(True) // Follow redirects automatically |> httpc.timeout(10_000) // 10 second timeout |> httpc.dispatch(req) case result { Ok(resp) -> { // Process successful response assert resp.status == 200 resp.body } Error(error) -> { // Handle error panic as "Request failed" } } } ``` -------------------------------- ### Send HTTP Request with gleam_httpc Source: https://github.com/gleam-lang/httpc/blob/main/README.md Demonstrates how to send an HTTP GET request using the gleam_httpc library. It shows how to prepare the request, add headers, send it, and then assert properties of the response like status code, content type, and body. This example requires the `gleam/http/request`, `gleam/http/response`, `gleam/httpc`, and `gleam/result` modules. ```gleam import gleam/http/request import gleam/http/response import gleam/httpc import gleam/result 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 assert resp.status == 200 let content_type = response.get_header(resp, "content-type") assert content_type == Ok("application/json") assert resp.body == "{\"message\":\"Hello World\"}" Ok(resp) } ``` -------------------------------- ### Basic HTTP GET Request Source: https://context7.com/gleam-lang/httpc/llms.txt Demonstrates how to send a simple HTTP GET request using default configurations. This is suitable for interacting with JSON APIs or text-based endpoints. ```APIDOC ## GET /hello/world ### Description Send a simple HTTP GET request to a specified URL with automatic configuration defaults. This function is ideal for interacting with JSON APIs and text-based endpoints. ### Method GET ### Endpoint /hello/world ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```gleam import gleam/http/request import gleam/httpc import gleam/result pub fn fetch_hello_world() { 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") use resp <- result.try(httpc.send(req)) Ok(resp) } ``` ### Response #### Success Response (200) - **body** (String) - The response body, typically JSON. - **headers** (List of { name: String, value: String }) - The response headers. - **status** (Int) - The HTTP status code. #### Response Example ```json { "message": "Hello World" } ``` ``` -------------------------------- ### Install gleam_httpc Source: https://github.com/gleam-lang/httpc/blob/main/README.md Command to add the gleam_httpc library to your Gleam project. This is the initial step to use the library's functionalities. ```shell gleam add gleam_httpc@5 ``` -------------------------------- ### Enable IPv6 Support for HTTP Requests in Gleam Source: https://context7.com/gleam-lang/httpc/llms.txt The HTTP client library automatically supports both IPv4 and IPv6 connections with transparent fallback. It attempts both connection types and uses whichever succeeds first. This example demonstrates making a request to an IPv6-only URL. ```gleam import gleam/http/request import gleam/httpc pub fn ipv6_request() { // This URL is IPv6 only let assert Ok(req) = request.to("https://ipv6.google.com") let assert Ok(resp) = httpc.send(req) assert 200 == resp.status } ``` -------------------------------- ### Basic HTTP GET Request with String Body in Gleam Source: https://context7.com/gleam-lang/httpc/llms.txt Performs a basic HTTP GET request using the gleam_httpc library. It demonstrates creating a request, adding headers, sending it with default configurations, and asserting the response status, headers, and body. This is suitable for interacting with JSON APIs or text-based endpoints. ```gleam import gleam/http/request import gleam/http/response import gleam/httpc import gleam/result pub fn fetch_hello_world() { // Create request to HMRC test API let assert Ok(base_req) = request.to("https://test-api.service.hmrc.gov.uk/hello/world") // Add custom headers let req = request.prepend_header(base_req, "accept", "application/vnd.hmrc.1.0+json") // Send request with default configuration use resp <- result.try(httpc.send(req)) // Check response status assert resp.status == 200 // Access response headers let content_type = response.get_header(resp, "content-type") assert content_type == Ok("application/json") // Access response body assert resp.body == "{\"message\":\"Hello World\"}" Ok(resp) } ``` -------------------------------- ### Send HEAD and OPTIONS Requests with Gleam HTTP Client Source: https://context7.com/gleam-lang/httpc/llms.txt Send HTTP HEAD and OPTIONS requests using the appropriate HTTP methods. These requests automatically discard request bodies, even if provided. Examples demonstrate sending a HEAD request to /get and an OPTIONS request to the same endpoint, verifying status codes and specific headers/bodies. ```gleam import gleam/http.{Head, Options} import gleam/http/request import gleam/http/response import gleam/httpc pub fn head_request_example() { let req = request.new() |> request.set_method(Head) |> request.set_host("postman-echo.com") |> request.set_path("/get") |> request.set_body("This gets dropped") let assert Ok(resp) = httpc.send(req) assert 200 == resp.status assert Ok("application/json; charset=utf-8") == response.get_header(resp, "content-type") assert "" == resp.body } pub fn options_request_example() { let req = request.new() |> request.set_method(Options) |> request.set_host("postman-echo.com") |> request.set_path("/get") |> request.set_body("This gets dropped") let assert Ok(resp) = httpc.send(req) assert 200 == resp.status assert Ok("text/html; charset=utf-8") == response.get_header(resp, "content-type") assert "GET,HEAD,PUT,POST,DELETE,PATCH" == resp.body } ``` -------------------------------- ### Handle Binary Data with Gleam HTTP Client Source: https://context7.com/gleam-lang/httpc/llms.txt Utilize `send_bits` and `dispatch_bits` for working with binary data (BitArray) instead of strings. This is essential for handling non-textual responses like images, PDFs, or binary protocols. The example shows creating a request with a binary body and sending it using both `send_bits` and `dispatch_bits` with configuration. ```gleam import gleam/bit_array import gleam/http/request.{type Request} import gleam/http/response.{type Response} import gleam/httpc pub fn binary_request_example() { // Create request with binary body let assert Ok(base_req) = request.to("https://api.example.com/data") let binary_body = bit_array.from_string("binary data") let req = request.set_body(base_req, binary_body) // Send with default configuration let assert Ok(resp) = httpc.send_bits(req) // Response body is BitArray let binary_response: BitArray = resp.body // Or use dispatch_bits with custom configuration let assert Ok(resp2) = httpc.configure() |> httpc.timeout(5000) |> httpc.dispatch_bits(req) } ``` -------------------------------- ### Configure HTTP Request Timeouts in Gleam Source: https://context7.com/gleam-lang/httpc/llms.txt Set custom timeout values for HTTP requests. The default timeout is 30 seconds. If the server doesn't respond within the timeout period, a ResponseTimeout error is returned. This example demonstrates setting a 5-second timeout and a 200ms timeout. ```gleam import gleam/http.{Get} import gleam/http/request import gleam/httpc pub fn timeout_examples() { let req = request.new() |> request.set_method(Get) |> request.set_host("httpbin.org") |> request.set_path("/delay/1") // Request with 5 second timeout (succeeds for 1 second delay) let assert Ok(resp) = httpc.configure() |> httpc.timeout(5000) |> httpc.dispatch(req) assert 200 == resp.status // Request with 200ms timeout (fails for 1 second delay) let result = httpc.configure() |> httpc.timeout(200) |> httpc.dispatch(req) assert result == Error(httpc.ResponseTimeout) } ``` -------------------------------- ### Set Custom User Agent Headers in Gleam HTTP Client Source: https://context7.com/gleam-lang/httpc/llms.txt Override the default user agent header (gleam_httpc/{version}) with a custom one. The library automatically adds a default user agent, but this can be replaced by setting the 'user-agent' header on the request. Examples show checking the default and setting a custom agent. ```gleam import gleam/http/request import gleam/httpc import gleam/string pub fn user_agent_examples() { // Default user agent is automatically added let assert Ok(req) = request.to("https://echo.free.beeceptor.com") let assert Ok(resp) = httpc.send(req) assert string.contains(resp.body, "\"User-Agent\": \"gleam_httpc/") // Override with custom user agent let assert Ok(req) = request.to("https://echo.free.beeceptor.com") let req = request.set_header(req, "user-agent", "gleam-test") let assert Ok(resp) = httpc.send(req) assert string.contains(resp.body, "\"User-Agent\": \"gleam-test") } ``` -------------------------------- ### Manual HTTP Request Building in Gleam Source: https://context7.com/gleam-lang/httpc/llms.txt Demonstrates building an HTTP request manually in Gleam using a builder pattern. This method offers granular control over the request's method, host, path, and headers before sending it via gleam_httpc. It includes verification of the response status and headers. ```gleam import gleam/http.{Get} import gleam/http/request import gleam/http/response import gleam/httpc pub fn manual_request() { let req = request.new() |> request.set_method(Get) |> request.set_host("test-api.service.hmrc.gov.uk") |> request.set_path("/hello/world") |> request.prepend_header("accept", "application/vnd.hmrc.1.0+json") let assert Ok(resp) = httpc.send(req) // Verify status code assert 200 == resp.status // Check specific header value assert response.get_header(resp, "content-type") == Ok("application/json") // Process response body assert resp.body == "{\"message\":\"Hello World\"}" } ``` -------------------------------- ### Manual HTTP Request Building Source: https://context7.com/gleam-lang/httpc/llms.txt Illustrates building an HTTP request manually, providing granular control over the method, host, path, and headers. ```APIDOC ## Manual Request Building ### Description Build an HTTP request manually using the request builder pattern. This approach offers more control over individual request components like method, host, path, and headers. ### Method GET (or other supported methods) ### Endpoint Customizable via `request.set_path` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```gleam import gleam/http.{Get} import gleam/http/request import gleam/httpc pub fn manual_request() { let req = request.new() |> request.set_method(Get) |> request.set_host("test-api.service.hmrc.gov.uk") |> request.set_path("/hello/world") |> request.prepend_header("accept", "application/vnd.hmrc.1.0+json") let assert Ok(resp) = httpc.send(req) Ok(resp) } ``` ### Response #### Success Response (200) - **body** (String) - The response body. - **headers** (List of { name: String, value: String }) - The response headers. - **status** (Int) - The HTTP status code. #### Response Example ```json { "message": "Hello World" } ``` ``` -------------------------------- ### HTTP Client Configuration Source: https://context7.com/gleam-lang/httpc/llms.txt Shows how to configure the HTTP client, including controlling TLS verification. This is crucial for security and can be adjusted for testing purposes. ```APIDOC ## HTTP Client Configuration (TLS Verification) ### Description Configure HTTP client behavior using the configuration builder. Control TLS certificate verification, which is critical for security but may need to be disabled for testing with self-signed or expired certificates. ### Method GET (or other supported methods) ### Endpoint Customizable via `request.to` or `request.new` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```gleam import gleam/http/request import gleam/httpc pub fn tls_verification_example() { let assert Ok(req) = request.to("https://expired.badssl.com") // Disable TLS verification (INSECURE - only for testing!) let assert Ok(response) = httpc.configure() |> httpc.verify_tls(False) |> httpc.dispatch(req) Ok(response) } ``` ### Response #### Success Response (200) - **body** (String) - The response body. - **headers** (List of { name: String, value: String }) - The response headers. - **status** (Int) - The HTTP status code. #### Response Example (Varies based on the target URL. For `https://expired.badssl.com` with verification disabled, it would be a 200 OK response.) ```json { "status": 200, "headers": [...], "body": "..." } ``` ``` -------------------------------- ### HEAD and OPTIONS Requests Source: https://context7.com/gleam-lang/httpc/llms.txt Send HTTP HEAD and OPTIONS requests. Request bodies are automatically discarded for these methods, even if provided. ```APIDOC ## HEAD and OPTIONS Requests ### Description Send HTTP HEAD and OPTIONS requests using the appropriate HTTP methods. These requests have special handling where request bodies are automatically discarded even if provided. ### Method HEAD, OPTIONS ### Endpoint `/get` (Example endpoint) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body (Ignored for HEAD and OPTIONS requests) ### Request Example ```gleam import gleam/http.{Head, Options} import gleam/http/request import gleam/http/response import gleam/httpc // HEAD Request Example let req_head = request.new() |> request.set_method(Head) |> request.set_host("postman-echo.com") |> request.set_path("/get") |> request.set_body("This gets dropped") let assert Ok(resp_head) = httpc.send(req_head) assert 200 == resp_head.status assert Ok("application/json; charset=utf-8") == response.get_header(resp_head, "content-type") assert "" == resp_head.body // OPTIONS Request Example let req_options = request.new() |> request.set_method(Options) |> request.set_host("postman-echo.com") |> request.set_path("/get") |> request.set_body("This gets dropped") let assert Ok(resp_options) = httpc.send(req_options) assert 200 == resp_options.status assert Ok("text/html; charset=utf-8") == response.get_header(resp_options, "content-type") assert "GET,HEAD,PUT,POST,DELETE,PATCH" == resp_options.body ``` ### Response #### Success Response (200) - **resp** (http.Response) - The HTTP response object. For HEAD, the body is typically empty. For OPTIONS, the body contains allowed HTTP methods. #### Response Example ```json // HEAD Response Example (Empty Body): // {} // OPTIONS Response Example: // GET,HEAD,PUT,POST,DELETE,PATCH ``` ``` -------------------------------- ### IPv6 Support Source: https://context7.com/gleam-lang/httpc/llms.txt The library automatically supports both IPv4 and IPv6 connections, attempting both and using the first one that succeeds. ```APIDOC ## IPv6 Support ### Description The library automatically supports both IPv4 and IPv6 connections with transparent fallback. It attempts both connection types and uses whichever succeeds. ### Method GET (implicitly via `httpc.send`) ### Endpoint `https://ipv6.google.com` (Example endpoint) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```gleam import gleam/http/request import gleam/httpc // This URL is IPv6 only let assert Ok(req) = request.to("https://ipv6.google.com") let assert Ok(resp) = httpc.send(req) assert 200 == resp.status ``` ### Response #### Success Response (200) - **resp** (http.Response) - The HTTP response object. #### Response Example ```json // Standard HTTP response object if the connection (IPv4 or IPv6) is successful. // Example: // { // "status": 200, // "headers": { ... }, // "body": "..." // } ``` ``` -------------------------------- ### Binary Request/Response Handling Source: https://context7.com/gleam-lang/httpc/llms.txt Utilize `send_bits` and `dispatch_bits` for working with binary data (BitArray) instead of strings, suitable for non-textual content like images or PDFs. ```APIDOC ## Binary Request/Response Handling ### Description Use `send_bits` and `dispatch_bits` for working with binary data (BitArray) instead of strings. This is useful for handling non-text responses like images, PDFs, or binary protocols. ### Method POST (implicitly via `httpc.send_bits` and `httpc.dispatch_bits`) ### Endpoint `/data` (Example endpoint) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **body** (BitArray) - The binary data to send in the request body. ### Request Example ```gleam import gleam/bit_array import gleam/http/request.{type Request} import gleam/http/response.{type Response} import gleam/httpc // Create request with binary body let assert Ok(base_req) = request.to("https://api.example.com/data") let binary_body = bit_array.from_string("binary data") let req = request.set_body(base_req, binary_body) // Send with default configuration let assert Ok(resp) = httpc.send_bits(req) // Response body is BitArray let binary_response: BitArray = resp.body // Or use dispatch_bits with custom configuration let assert Ok(resp2) = httpc.configure() |> httpc.timeout(5000) |> httpc.dispatch_bits(req) ``` ### Response #### Success Response (200) - **resp** (http.Response) - The HTTP response object with its body as a `BitArray`. #### Response Example ```json // The resp.body will be a BitArray containing the binary response content. // Example representation (actual content depends on the response): // ``` ``` -------------------------------- ### Controlling TLS Verification in Gleam HTTP Requests Source: https://context7.com/gleam-lang/httpc/llms.txt Illustrates how to configure TLS certificate verification for HTTP requests using gleam_httpc. It shows the default behavior (verification enabled), explicit enabling, and disabling verification for testing purposes. Disabling TLS verification is noted as insecure and should only be used in testing environments. ```gleam import gleam/http/request import gleam/httpc pub fn tls_verification_example() { let assert Ok(req) = request.to("https://expired.badssl.com") // Default behavior: TLS verification enabled (will fail for invalid certs) let assert Error(httpc.FailedToConnect( ip4: httpc.TlsAlert("certificate_expired", _), ip6: _, )) = httpc.send(req) // Explicit TLS verification enabled (same as default) let assert Error(httpc.FailedToConnect( ip4: httpc.TlsAlert("certificate_expired", _), ip6: _, )) = httpc.configure() |> httpc.verify_tls(True) |> httpc.dispatch(req) // Disable TLS verification (INSECURE - only for testing!) let assert Ok(response) = httpc.configure() |> httpc.verify_tls(False) |> httpc.dispatch(req) assert 200 == response.status } ``` -------------------------------- ### Handling HTTP Redirects in Gleam Source: https://context7.com/gleam-lang/httpc/llms.txt Explains how to manage HTTP redirects (3xx status codes) when making requests with gleam_httpc. It demonstrates the default behavior where redirects are not automatically followed, explicitly disabling redirects, and enabling them to reach the final destination URL. This allows for controlled redirect resolution. ```gleam import gleam/http/request import gleam/httpc pub fn redirect_handling() { // URL that redirects from HTTP to HTTPS let assert Ok(req) = request.to("http://packages.gleam.run") // Default: redirects NOT followed (returns 308 status) let assert Ok(resp) = httpc.send(req) assert 308 == resp.status // Explicitly disable redirect following let assert Ok(resp) = httpc.configure() |> httpc.follow_redirects(False) |> httpc.dispatch(req) assert 308 == resp.status // Enable redirect following (follows to final destination) let assert Ok(resp) = httpc.configure() |> httpc.follow_redirects(True) |> httpc.dispatch(req) assert 200 == resp.status } ``` -------------------------------- ### HTTP Redirect Handling Source: https://context7.com/gleam-lang/httpc/llms.txt Explains how to control whether the HTTP client automatically follows redirect responses (3xx status codes). By default, redirects are not followed. ```APIDOC ## HTTP Redirect Handling ### Description Control whether the HTTP client automatically follows redirect responses (3xx status codes). By default, redirects are not followed, giving you full control over redirect handling. ### Method GET (or other supported methods) ### Endpoint Customizable via `request.to` or `request.new` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```gleam import gleam/http/request import gleam/httpc pub fn redirect_handling() { // URL that redirects from HTTP to HTTPS let assert Ok(req) = request.to("http://packages.gleam.run") // Enable redirect following (follows to final destination) let assert Ok(resp) = httpc.configure() |> httpc.follow_redirects(True) |> httpc.dispatch(req) Ok(resp) } ``` ### Response #### Success Response (200) - **body** (String) - The response body from the final destination after redirects. - **headers** (List of { name: String, value: String }) - The response headers. - **status** (Int) - The HTTP status code (typically 200 if redirects are followed successfully). #### Response Example (Assuming successful redirect to a page with content) ```json { "status": 200, "headers": [...], "body": "..." } ``` ``` -------------------------------- ### Handle HTTP Errors in Gleam Source: https://context7.com/gleam-lang/httpc/llms.txt Demonstrates handling various HTTP errors like connection failures, TLS alerts, timeouts, and invalid UTF-8 responses using the HttpError type in Gleam. It shows how to pattern match on different error variants returned by `httpc.send`. ```gleam import gleam/http/request import gleam/httpc import gleam/io pub fn error_handling_example() { let assert Ok(req) = request.to("https://expired.badssl.com") case httpc.send(req) { Ok(resp) -> { io.println("Success: " <> resp.body) } Error(httpc.InvalidUtf8Response) -> { io.println("Response contained non-UTF-8 data") } Error(httpc.FailedToConnect(ip4: ip4_error, ip6: ip6_error)) -> { case ip4_error { httpc.Posix(code) -> io.println("IPv4 POSIX error: " <> code) httpc.TlsAlert(code, detail) -> io.println("IPv4 TLS alert: " <> code <> " - " <> detail) } } Error(httpc.ResponseTimeout) -> { io.println("Request timed out") } } } ``` -------------------------------- ### Request Timeout Configuration Source: https://context7.com/gleam-lang/httpc/llms.txt Configure custom timeout values for HTTP requests. The default is 30 seconds, but it can be adjusted. A ResponseTimeout error is returned if the server does not respond within the specified period. ```APIDOC ## Request Timeout Configuration ### Description Set custom timeout values for HTTP requests. The default timeout is 30 seconds, but you can adjust it based on your needs. If the server doesn't respond within the timeout period, a ResponseTimeout error is returned. ### Method POST (implicitly via `httpc.configure` and `httpc.dispatch`) ### Endpoint N/A (Configuration applied to request dispatch) ### Parameters #### Query Parameters None #### Request Body None ### Request Example ```gleam import gleam/httpc import gleam/http/request let req = request.new() |> request.set_method(gleam.http.Get) |> request.set_host("httpbin.org") |> request.set_path("/delay/1") // Request with 5 second timeout (succeeds for 1 second delay) let assert Ok(resp) = httpc.configure() |> httpc.timeout(5000) |> httpc.dispatch(req) assert 200 == resp.status // Request with 200ms timeout (fails for 1 second delay) let result = httpc.configure() |> httpc.timeout(200) |> httpc.dispatch(req) assert result == Error(httpc.ResponseTimeout) ``` ### Response #### Success Response (200) - **resp** (http.Response) - The HTTP response object. #### Response Example ```json // For successful requests, the response object is returned. // For timeouts, an Error(httpc.ResponseTimeout) is returned. ``` ``` -------------------------------- ### Custom User Agent Headers Source: https://context7.com/gleam-lang/httpc/llms.txt Override the default user agent header ('gleam_httpc/{version}') by setting your own user-agent header on the request. ```APIDOC ## Custom User Agent Headers ### Description The library automatically sets a default user agent header with the format "gleam_httpc/{version}". You can override this by setting your own user-agent header on the request. ### Method POST (implicitly via `httpc.send`) ### Endpoint N/A (Header applied to outgoing request) ### Parameters #### Query Parameters None #### Request Body None ### Request Example ```gleam import gleam/http/request import gleam/httpc import gleam/string // Default user agent is automatically added let assert Ok(req) = request.to("https://echo.free.beeceptor.com") let assert Ok(resp) = httpc.send(req) assert string.contains(resp.body, "\"User-Agent\": \"gleam_httpc/") // Override with custom user agent let assert Ok(req) = request.to("https://echo.free.beeceptor.com") let req = request.set_header(req, "user-agent", "gleam-test") let assert Ok(resp) = httpc.send(req) assert string.contains(resp.body, "\"User-Agent\": \"gleam-test") ``` ### Response #### Success Response (200) - **resp** (http.Response) - The HTTP response object. #### Response Example ```json // The response body will contain the headers sent, including the User-Agent. // Example for default: // { // "headers": { // "User-Agent": "gleam_httpc/0.1.0" // } // } // Example for custom: // { // "headers": { // "User-Agent": "gleam-test" // } // } ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.