I am trying to make a prolog api where I call a given prolog link from another program. After several tries and learning prolog, this is the best version of the code I've been able to write
#!/usr/bin/env swipl
:- use_module(library(http/thread_httpd)).
:- use_module(library(http/http_dispatch)).
:- use_module(library(http/http_client)).
:- initialization main.
:- http_handler(/, index, []).
:- http_handler('/test', test, []).
:- http_handler('/reply', reply, []).
index(_Request) :-
format('Content-type: text/plain~n~n'),
format('Hello World!~n').
test(_Request) :-
format('Content-type: text/plain~n~n'),
format('This is another test, trying to make multiple links!~n').
reply(Request) :-
member(method(post), Request), !,
http_read_data(Request, Data, []),
format('Content-type: text/plain~n~n'),
format('This is where the data should be displayed!~n').
/*print(Data).*/
main :-
http_server(http_dispatch, [port(3000)]),
thread_get_message(quit).
The main function which is reply gives me an internal server error and Syntax error: illegal_uri_query When I omit this line: http_read_data(Request, Data, []), everything works so I believe there is something about this that I can't figure out.
Note: the data I'm sending is just a string through the following code written in laravel:
$ch = curl_init('http://localhost:3000/reply');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonStr);
// execute!
$response = curl_exec($ch);
// close the connection, release resources used
curl_close($ch);
This code works well for the other two pages index and test.
Make sure to indicate that you send a JSON data by adding content-type
curl_setopt( $ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));