I cannot seem to get http_parameters to work and I’m not sure why (swipl 8.0.3 64bit). I’ve created a tiny server example below, which I test from the linux commandline with httpie (like curl, but nicer interface). When I debug the Request data, it looks like the JSON data has disappeared, but I’m not how that happens.
Here is the code for the tiny server (and the interchange with the server below that):
% http libraries
:- use_module(library(settings)).
:- use_module(library(http/thread_httpd)).
:- use_module(library(http/http_dispatch)).
:- use_module(library(http/http_path)).
:- use_module(library(http/http_parameters)).
:- use_module(library(http/json)).
:- use_module(library(http/json_convert)).
:- use_module(library(http/http_json)).
:- use_module(library(debug)).
% handler declarations
:- http_handler(root(.), frontpage,[prefix]).
% server
server:-
open('log.txt',append, ErrStream,[]),
debug(server>ErrStream),
http_server(http_dispatch,[port(8080)]).
stopserver:- http_stop_server(8080,[]).
frontpage(Request):-
http_parameters(Request,[
email(Email, [optional(true)]),
password(_Passwd, [optional(true)])
]),
debug(server,'~w',[Request]),
(var(Email)->Email='empty email field';true),
reply_json( json([user=Email]) ),!.
With httpie, on the commandline, I fire a POST request (also tried GET and PUT) as follows:
http -v POST :8080 email=john@mail.com password=fubar
This causes httpie to send the following to the server:
POST / HTTP/1.1
Accept: application/json, */*
Accept-Encoding: gzip, deflate
Connection: keep-alive
Content-Length: 47
Content-Type: application/json
Host: localhost:8080
User-Agent: HTTPie/0.9.8
{
"email": "john@mail.com",
"password": "fubar"
}
And the server responds as follows:
HTTP/1.1 200 OK
Connection: keep-alive
Content-Length: 28
Content-Type: application/json; charset=UTF-8
Date: Fri, 20 Mar 2020 06:47:03 GMT
{
"user": "empty email field"
}
When I inspect the log file, the contents of the Request are as follows:
% [Thread httpd@8080_13] [protocol(http),peer(ip(127,0,0,1)),pool(client(httpd@8080,user:http_dispatch,<stream>(0x7f07b0
023070),<stream>(0x7f07b0011af0))),input(<stream>(0x7f07b0023070)),method(post),request_uri(/),path(/),http_version(1-1)
,host(localhost),port(8080),user_agent(HTTPie/0.9.8),accept_encoding(gzip, deflate),accept([media(application/json,[],1.
0,[]),media(_2460/_2462,[],1.0,[])]),connection(keep-alive),content_type(application/json),content_length(47)]