3 # Copyright 2008 LibLime
5 # This file is part of Koha.
7 # Koha is free software; you can redistribute it and/or modify it
8 # under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 3 of the License, or
10 # (at your option) any later version.
12 # Koha is distributed in the hope that it will be useful, but
13 # WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
17 # You should have received a copy of the GNU General Public License
18 # along with Koha; if not, see <http://www.gnu.org/licenses>.
22 C4::Service - functions for JSON webservices.
26 my ( $query, $response) = C4::Service->init( { circulate => 1 } );
27 my ( $borrowernumber) = C4::Service->require_params( 'borrowernumber' );
29 C4::Service->return_error( 'internal', 'Frobnication failed', frobnicator => 'foo' );
31 $response->param( frobnicated => 'You' );
33 C4::Service->return_success( $response );
37 This module packages several useful functions for JSON webservices.
45 use C4::Auth qw( check_api_auth );
46 use C4::Output qw( output_with_http_headers );
47 use C4::Output::JSONStream;
50 our ( $query, $cookie );
53 my ( $response, $status ) = @_;
54 binmode STDOUT, ':encoding(UTF-8)';
56 if ( $query->param( 'callback' ) ) {
57 output_with_http_headers $query, $cookie, $query->param( 'callback' ) . '(' . $response->output . ');', 'js';
59 output_with_http_headers $query, $cookie, $response->output, 'json', $status;
67 our ( $query, $response ) = C4::Service->init( %needed_flags );
69 Initialize the service and check for the permissions in C<%needed_flags>.
71 Also, check that the user is authorized and has a current session, and return an
74 init() returns a C<CGI> object and a C<C4::Output::JSONStream>. The latter can
75 be used for both flat scripts and those that use dispatch(), and should be
76 passed to C<return_success()>.
81 my ( $class, %needed_flags ) = @_;
83 our $query = CGI->new;
85 my ( $status, $cookie_, $sessionID ) = check_api_auth( $query, \%needed_flags );
87 our $cookie = $cookie_; # I have no desire to offend the Perl scoping gods
89 $class->return_error( 'auth', $status ) if ( $status ne 'ok' );
91 return ( $query, C4::Output::JSONStream->new );
96 C4::Service->return_error( $type, $error, %flags );
98 Exit the script with HTTP status 400, and return a JSON error object.
100 C<$type> should be a short, lower case code for the generic type of error (such
101 as 'auth' or 'input').
103 C<$error> should be a more specific code giving information on the error. If
104 multiple errors of the same type occurred, they should be joined by '|'; i.e.,
105 'expired|different_ip'. Information in C<$error> does not need to be
106 human-readable, as its formatting should be handled by the client.
108 Any additional information to be given in the response should be passed as
109 param => value pairs.
114 my ( $class, $type, $error, %flags ) = @_;
116 my $response = C4::Output::JSONStream->new;
118 $response->param( message => $error ) if ( $error );
119 $response->param( type => $type, %flags );
121 _output( $response, '400 Bad Request' );
127 C4::Service->return_multi( \@responses, %flags );
129 return_multi is similar to return_success or return_error, but allows you to
130 return different statuses for several requests sent at once (using HTTP status
131 "207 Multi-Status", much like WebDAV). The toplevel hashref (turned into the
132 JSON response) looks something like this:
134 { multi => JSON::true, responses => \@responses, %flags }
136 Each element of @responses should be either a plain hashref or an arrayref. If
137 it is a hashref, it is sent to the browser as-is. If it is an arrayref, it is
138 assumed to be in the same form as the arguments to return_error, and is turned
139 into an error structure.
141 All key-value pairs %flags are, as stated above, put into the returned JSON
147 my ( $class, $responses, @flags ) = @_;
149 my $response = C4::Output::JSONStream->new;
151 if ( !@$responses ) {
152 $class->return_success( $response );
154 my @responses_formatted;
156 foreach my $response ( @$responses ) {
157 if ( ref( $response ) eq 'ARRAY' ) {
158 my ($type, $error, @error_flags) = @$response;
160 push @responses_formatted, { is_error => JSON::true, type => $type, message => $error, @error_flags };
162 push @responses_formatted, $response;
166 $response->param( 'multi' => JSON::true, responses => \@responses_formatted, @flags );
167 _output( $response, '207 Multi-Status' );
173 =head2 return_success
175 C4::Service->return_success( $response );
177 Print out the information in the C<C4::Output::JSONStream> C<$response>, then
178 exit with HTTP status 200.
183 my ( $class, $response ) = @_;
185 _output( $response );
188 =head2 require_params
190 my @values = C4::Service->require_params( @params );
192 Check that each of of the parameters specified in @params was sent in the
193 request, then return their values in that order.
195 If a required parameter is not found, send a 'param' error to the browser.
200 my ( $class, @params ) = @_;
204 for my $param ( @params ) {
205 $class->return_error( 'params', "Missing '$param'" ) if ( !defined( $query->param( $param ) ) );
206 push @values, scalar $query->param( $param ); # will we ever need multi_param here?
214 C4::Service->dispatch(
215 [ $path_regex, \@required_params, \&handler ],
219 dispatch takes several array-refs, each one describing a 'route', to use the
222 $path_regex should be a string in regex-form, describing which methods and
223 paths this route handles. Each route is tested in order, from the top down, so
224 put more specific handlers first. Also, the regex is tested on the request
225 method, plus the path. For instance, you might use the route [ 'POST /', ... ]
226 to handle POST requests to your service.
228 Each named parameter in @required_params is tested for to make sure the route
229 matches, but does not raise an error if one is missing; it simply tests the next
230 route. If you would prefer to raise an error, instead use
231 C<C4::Service->require_params> inside your handler.
233 \&handler is called with each matched group in $path_regex in its arguments. For
234 example, if your service is accessed at the path /blah/123, and you call
235 C<dispatch> with the route [ 'GET /blah/(\\d+)', ... ], your handler will be called
236 with the argument '123'.
243 my $path_info = $query->path_info || '/';
245 ROUTE: foreach my $route ( @_ ) {
246 my ( $path, $params, $handler ) = @$route;
248 next unless ( my @match = ( ($query->request_method . ' ' . $path_info) =~ m,^$path$, ) );
250 for my $param ( @$params ) {
251 next ROUTE if ( !defined( $query->param ( $param ) ) );
254 $handler->( @match );
258 $class->return_error( 'no_handler', '' );
267 Koha Development Team
269 Jesse Weaver <jesse.weaver@liblime.com>