File: demo_rest.pl

package info (click to toggle)
swi-prolog 9.0.4%2Bdfsg-2
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 82,408 kB
  • sloc: ansic: 387,503; perl: 359,326; cpp: 6,613; lisp: 6,247; java: 5,540; sh: 3,147; javascript: 2,668; python: 1,900; ruby: 1,594; yacc: 845; makefile: 428; xml: 317; sed: 12; sql: 6
file content (56 lines) | stat: -rw-r--r-- 1,565 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
:- module(demo_http_rest,
          [ server/1                            % +Port
          ]).
:- use_module(library(http/thread_httpd)).
:- use_module(library(http/http_dispatch)).

server(Port) :-
    http_server(http_dispatch,
                [ port(Port)
                ]).

/** <module> Demonstrate dispatching using wildcarts

This example demonstrates dispatching events   using wildcarts, normally
used for REST APIs. To run this  test,   start  the server and use e.g.,
`curl` as:

```
curl http://localhost:5000/user/jan
curl http://localhost:5000/user/default
curl http://localhost:5000/user/jan/parents
```

Note that the predicate http_link_to_id/3 can   generate URLs that refer
to these handlers. For example:

    ?- http_link_to_id(parents('Bob'), [], URL).
    URL = '/user/Bob/parents'.

The library(http/html_write) can generate also   generate links to these
handlers, for example:

    ...,
    html(a(href(#(user('Bob'))), 'Bob'))

produces

    <a href="/user/Bob">Bob</a>
*/

:- http_handler(root(user/User),         user(M, User), [method(M)]).
:- http_handler(root(user/default),      default_user,  []).
:- http_handler(root(user/User/parents), parents(User), []).

user(Method, User, _Request) :-
    format('Content-type: text/plain~n~n'),
    format('Run method ~p on user ~p~n', [Method, User]).

default_user(_Request) :-
    format('Content-type: text/plain~n~n'),
    format('Send a default user~n', []).

parents(User, _Request) :-
    format('Content-type: text/plain~n~n'),
    format('Asked for parents for ~p~n', [User]).