Search code examples
schemeguile

How do you get the response data as string using (web client) in guile?


I'm trying to get the response data as a string using the docs found here https://www.gnu.org/software/guile/manual/html_node/Web-Client.html.

The document mentions that http-request:

Returns two values: the response read from the server, and the response body as a string, bytevector, #f value, or as a port ....

However, its not clear to me how to actually extract the string value. I can get the port, but not a plain string as mentioned in the docs.

(define response 
  (http-request (string-append "http://localhost:" port "/save")
                #:method 'POST 
                #:headers '((Content-Type . "application/json")) 
                #:streaming? #f
                #:decode-body? #t
                #:body (string->utf8 body)))

  (response-body-port response)

Solution

  • The concept of multiple values in Guile (Scheme) is not common in other programming languages (ahead of its time :p).

    You pointed out there are two return values. So let's get those two values. You can read more details here : https://www.gnu.org/software/guile/manual/guile.html#Multiple-Values

    In the meantime, here is what I have tested using the Guile reference example :

    (use-modules (web client))
    (use-modules (ice-9 receive))
    
    (receive (response-status response-body)
        (http-request "http://www.gnu.org")
      (display response-body))
    

    I gave two "formal arguments" to receive to bind to the two return values of http-request. But I only use the second, aka response-body (as a string to display) because it is the one you where looking for.

    Hope it helps !

    P.S: Guile hackers are more active in the Guile mailing list than on StackOverflow. I'm watching, but I'm not your best asset haha.

    Happy hacking !