Sybren
Sybren

Reputation: 1079

Prolog http get request with request headers

I trying to do a http get request with request headers with prolog but I can't find out how to do it exacly.

Here's an example how to do it in Python:

response = unirest.get("https://poker.p.mashape.com/index.php?players=3",
headers={
"X-Mashape-Key": "mykey",
"Accept": "application/json"
}

The response of this request is in Json and looks like:

{
"player_cards": {
"1": [
  "Jh",
  "4c"
],
"2": [
  "3s",
  "Js"
],
"3": [
  "3d",
  "5c"
],
"4": [
  "Kh",
  "Qs"
]
},
"showdown": [
"Ks",
"6h",
"4s",
"Ac",
"9h"
],
"winning_hands": {
"1": [
  "4c",
  "4s",
  "Ac",
  "Ks",
  "Jh"
],
"2": [
  "Ac",
  "Ks",
  "Js",
  "9h",
  "6h"
],
"3": [
  "Ac",
  "Ks",
  "9h",
  "6h",
  "5c"
],
"4": [
  "Kh",
  "Ks",
  "Ac",
  "Qs",
  "9h"
]
},
"winners": [
4
]
}

My prolog code

poker(Players) :-
format(atom(HREF),'https://poker.p.mashape.com/index.php?players=~s',[Players]),
http_get(HREF,Json,[]),

How to specify the http get request headers here and how can I store and use the Json result? The function has to print the Json result, I know this can be done by writeln().

Upvotes: 3

Views: 1888

Answers (1)

Wouter Beek
Wouter Beek

Reputation: 3407

I you want to specify HTTP request headers I would advise using http_open/3 i.o. http_get/3. For example:

:- use_module(library(http/http_open)).
:- use_module(library(http/json)).

poker(Dict):-
  setup_call_cleanup(
    http_open('https://poker.p.mashape.com/index.php?players=3', In, [request_header('Accept'='application/json')]),
    json_read_dict(In, Dict),
    close(In)
  ).

Notice my use of setup_call_cleanup/3. This ensures that the stream gets closed even if the code in the middle fails or throws an exception.

json_read_dict/2 returns a SWI7 dictionary. You need SWI-Prolog version 7 for this! Preferably the latest commit from the development branch.

It seems that the URI you are using requires SSL authentication. I believe it is possible to get this working in SWI-Prolog as well, but I could not find an example of how to do this. See my question to the SWI-Prolog mailinglist on this.

Upvotes: 3

Related Questions