Mojolicious and REST

11
Mojolicious and REST Building a RESTful interface using Mojolicious By @jonasbn for Nordic Perl Workshop 2013

description

Lessons learning from implementing a RESTful interface using Mojolicious

Transcript of Mojolicious and REST

Page 1: Mojolicious and REST

Mojolicious and REST Building a RESTful interface using Mojolicious

By @jonasbn for Nordic Perl Workshop 2013

Page 2: Mojolicious and REST

- $authbridge->route(‘/domain/is_available/:domainname')

+ $authbridge->route(‘/domain/is_available/#domainname')

Page 3: Mojolicious and REST

• Implementing REST using Mojolicious is easy

• very easy

• too easy

Page 4: Mojolicious and REST

but!

Page 5: Mojolicious and REST

Rest in Practice

Ian Robinson, Jim Webber and Savas Parastatides

• On mediatypes, describes an anti-pattern implemented in Ruby on Rails

Page 6: Mojolicious and REST

• On mediatypes, describes an anti-pattern implemented in Ruby on Rails (RoR)

• This pattern has unfortunately made it to Mojolicious

• and that is to have the media-type communicated on the URL

Page 7: Mojolicious and REST

so?

Page 8: Mojolicious and REST

• The recommended practice is to use Accept headers to communicate media-types

• and these can be weighted 8-o

• We use HTTP status codes to communicate state and status

• URLs should be used to communicate intent not formatting

• For Mojolicious this required some experimenting

Page 9: Mojolicious and REST

code?

Page 10: Mojolicious and REST

$self->respond_to( json => { status => $status, json => $response }, text => { status => $status, text => $message }, xml => { status => $status, text => XMLout( $response, NoAttr => TRUE, RootName => XML_ROOT, keyattr => [], XMLDecl => XML_DECL ) }, any => { status => HTTP_UNSUPPORTED_MEDIA_TYPE, json => status_message(HTTP_UNSUPPORTED_MEDIA_TYPE) }, );

Page 11: Mojolicious and REST

Lessons Learned• Mojolicious does the right thing when it comes to the

Accept header and actually does it quite well

• The anti-pattern supported by Mojolicious can be avoided

• Use # instead of : in your routes (see the diff) and it will work

• But actually ?format=(json|text|xml) is supported but we only use it for debugging (and it actually has precedence (and it is undocumented on our side))