SlideShare une entreprise Scribd logo
1  sur  13
Télécharger pour lire hors ligne
RESTful Web Services
with Mojolicious and DBIx::Class
About me
●   Tudor Constantin


●   Perl Developer @ Evozon
●   http://programming.tudorconstantin.com/
●   http://stackoverflow.com/users/459233/tudor-constantin
●   https://github.com/tudorconstantin
●   http://www.linkedin.com/in/tudorconstantin
●   twitter: @tudorconstantin
●   gmail: tudorconstantin at gmail dot com
Content
●   Sample app overview - Expense Tracker
●   (Short) Intro to RESTful Web Services
●   DBIx::Class
●   Mojolicious
●   Routing in Mojo
●   Generic Mojo Controller for CRUD operations
●   Sample operation - update user
●   Steps for getting RESTful routes/operations for a table in DB
Sample app Expense
Tracker
VERY simple application - but usable (insert expenses, assign categories and
see reports)

●   Five tables
     ○ users
     ○ currencies
     ○ categories
     ○ operations
     ○ operations_categories

●   Relationships
     ○ 1 user has many categories
     ○ 1 user has many operations
     ○ 1 category has many sub categories
     ○ 1 category has many operations
     ○ 1 operation has many categories
     ○ 1 operation has a currency
1 operation belongs to a user
Intro to RESTful Web
Services
REST - REpresentational State Transfer
 ● concept introduced in 2000 by Roy Fielding in his academic dissertation,
    "Architectural Styles and the Design of Network-based Software Architectures"

Main ideas for REST:
● Resources are accessible through unique URLs:
     ○ /user/23
     ○ /operations
● Use HTTP methods explicitly
     ○ GET           - for Read
     ○ POST          - for Create
     ○ PUT           - for Update
     ○ DELETE        - for Delete
● Be stateless
     ○ the server does not know nor cares about the state of the client
        application
● Transfer Representations of resources (HTML, JSON, XML, etc)
DBIx::Class
●   An abstraction for working with DBs
●   More than an ORM (Object Relational Mapper) - It knows how to work on
    Result Sets
●   Components - simplified overview:
     ○ DBIx::Class::Schema - connection to DB
     ○ DBIx::Class::ResultSet - a query used for fetching a set of results
     ○ DBIx::Class::Row - objects returned from DBIx::Class::ResultSets
        using the create, find, next and all methods
●   Sample usage:
     my @rows = ExpenseTracker::Models->connect(
                          $config->{database}->{ $mode }->{dsn},
                          $config->{database}->{ $mode }->{user},
                          $config->{database}->{ $mode }->{password},
         )                                                       # DBIx::Class::Schema
       ->resultset( 'ExpenseTracker::Models::Result::User' )  # DBIx::Class::ResultSet
       ->search_rs(
           { id => 10 },
       )                                                         # DBIx::Class::ResultSet - only users
    with id = 10
       ->all();                                                  # The collection of DBIx::Class::Row
    instances
Mojolicious
●   Microframework inspired by Sinatra (Ruby)
●   Components of interest (for this app)
     ○ Router
     ○ Controller
●   Not (quite) interested in:
     ○ Views (since we render mainly json)
●   Not provided at all:
     ○ Models (we plug in and use DBIx::Class)
Routing in Mojolicious
In app context (ie - the startup routine):
my $r = $self->routes;
#sample route named 'login' for GET - executing method login from controller ExpenseTracker::Controllers::Login
$r->get('/login')->to('login#login')->name('login');



Shortcut, generic routing:
$params->{app_routes}->add_shortcut(resource => sub {
  my ($r, $name ) = @_;
  # Generate route for "/$name" - Controller is ExpenseTracker::Controller::camelize($name)
  my $resource = $r->route( "/$name" )->to("$name#");

  # Handle POST requests - will hit the create method in controller
  $resource->post->to('#create')->name("create_$name");
  # Handle GET requests - lists the collection of this resource - hits the list method in controller
  $resource->get->to('#list')->name("list_$name");

  $resource = $r->route( "/$name/:id" )->to("$name#");

  $resource->get->to('#show')->name("show_$name");
  $resource->delete->to('#remove')->name("delete_$name");
  $resource->put->to('#update')->name("update_$name");



  return $resource;
 });
Generic Controller for CRUD
Operations
●   Each resource needs a controller responsible for it
●   Each of those controllers will have to implement at least 7 actions:
     ○ create - POST /resource_name - creates a new resource
     ○ update - PUT /resource_name/:id - updates a resource
     ○ list      - GET /resource_name - show the collection of resources
     ○ show - GET /resource_name/:id - get the resource with id :id
     ○ remove - DELETE /resource_name/:id - annihilate resource :id
●   Possible approaches
     ○ create a Moose role that will expose all those methods and use this
        role (I guess)
     ○ implement a basic controller that will be inherited by all the other
        resource controller
Sample op - update user
In child controller (ExpenseTracker::Controller::User)
=head update
 sample of overriding a default update method
route here: PUT /user/:id
=cut
sub update{
  my $self = shift;

    return $self->render(status => 405, json => {message => 'You can only update your own profile!!!'} )
     if ( !defined $self->param('id') or !defined $self->app->user or $self->param('id') != $self->app->user->id );

    return $self->SUPER::update(@_);
}
Sample op - update user
In base controller ExpenseTracker::Controllers::Base - the one that
ExpenseTracker::Controllers::User inherits from:
sub update{
 my $self = shift;

    my $result_rs = $self->app->model
     ->resultset( $self->{resource} )
     ->search_rs(
        { id => $self->param('id') },
     );

    return $self->render_not_found if ( scalar( ( $result_rs->all ) ) == 0 );

    $result_rs->update_all( $self->req->json );

    $result_rs->result_class('DBIx::Class::ResultClass::HashRefInflator');
    my @result = $result_rs->all();
    return $self->render_json( [ @result ] );
}
Steps for getting RESTful
routes/operations
●   Generate the DBIx::Class model based on the DB table, with DBIx::
    Class::Schema::Loader
●   Create a controller that inherits from ExpenseTracker::Controllers::Base
●   Add the resource name to the conf.yml
The End
Fork the sample app and play with it:



https://github.com/tudorconstantin/expense-tracker

Contenu connexe

Tendances

Web Apps in Perl - HTTP 101
Web Apps in Perl - HTTP 101Web Apps in Perl - HTTP 101
Web Apps in Perl - HTTP 101hendrikvb
 
Mojolicious - Perl Framework for the Real-Time Web (Lightning Talk)
Mojolicious - Perl Framework for the Real-Time Web (Lightning Talk)Mojolicious - Perl Framework for the Real-Time Web (Lightning Talk)
Mojolicious - Perl Framework for the Real-Time Web (Lightning Talk)Dotan Dimet
 
Mojolicious. Веб в коробке!
Mojolicious. Веб в коробке!Mojolicious. Веб в коробке!
Mojolicious. Веб в коробке!Anatoly Sharifulin
 
Webrtc mojo
Webrtc mojoWebrtc mojo
Webrtc mojobpmedley
 
Mojolicious, real-time web framework
Mojolicious, real-time web frameworkMojolicious, real-time web framework
Mojolicious, real-time web frameworktaggg
 
Keeping it small - Getting to know the Slim PHP micro framework
Keeping it small - Getting to know the Slim PHP micro frameworkKeeping it small - Getting to know the Slim PHP micro framework
Keeping it small - Getting to know the Slim PHP micro frameworkJeremy Kendall
 
YAPC::Asia 2010 Twitter解析サービス
YAPC::Asia 2010 Twitter解析サービスYAPC::Asia 2010 Twitter解析サービス
YAPC::Asia 2010 Twitter解析サービスYusuke Wada
 
Slim RedBeanPHP and Knockout
Slim RedBeanPHP and KnockoutSlim RedBeanPHP and Knockout
Slim RedBeanPHP and KnockoutVic Metcalfe
 
Keeping it small: Getting to know the Slim micro framework
Keeping it small: Getting to know the Slim micro frameworkKeeping it small: Getting to know the Slim micro framework
Keeping it small: Getting to know the Slim micro frameworkJeremy Kendall
 
Building Modern and Secure PHP Applications – Codementor Office Hours with Be...
Building Modern and Secure PHP Applications – Codementor Office Hours with Be...Building Modern and Secure PHP Applications – Codementor Office Hours with Be...
Building Modern and Secure PHP Applications – Codementor Office Hours with Be...Arc & Codementor
 
Keeping it Small: Getting to know the Slim Micro Framework
Keeping it Small: Getting to know the Slim Micro FrameworkKeeping it Small: Getting to know the Slim Micro Framework
Keeping it Small: Getting to know the Slim Micro FrameworkJeremy Kendall
 
エロサイト管理者の憂鬱3 - Hokkaiodo.pm#4 -
エロサイト管理者の憂鬱3 - Hokkaiodo.pm#4 -エロサイト管理者の憂鬱3 - Hokkaiodo.pm#4 -
エロサイト管理者の憂鬱3 - Hokkaiodo.pm#4 -Yusuke Wada
 
Twib in Yokoahma.pm 2010/3/5
Twib in Yokoahma.pm 2010/3/5Twib in Yokoahma.pm 2010/3/5
Twib in Yokoahma.pm 2010/3/5Yusuke Wada
 
Asynchronous programming patterns in Perl
Asynchronous programming patterns in PerlAsynchronous programming patterns in Perl
Asynchronous programming patterns in Perldeepfountainconsulting
 
Extending the WordPress REST API - Josh Pollock
Extending the WordPress REST API - Josh PollockExtending the WordPress REST API - Josh Pollock
Extending the WordPress REST API - Josh PollockCaldera Labs
 
Using the new WordPress REST API
Using the new WordPress REST APIUsing the new WordPress REST API
Using the new WordPress REST APICaldera Labs
 
PerlでWeb API入門
PerlでWeb API入門PerlでWeb API入門
PerlでWeb API入門Yusuke Wada
 
Connecting Content Silos: One CMS, Many Sites With The WordPress REST API
 Connecting Content Silos: One CMS, Many Sites With The WordPress REST API Connecting Content Silos: One CMS, Many Sites With The WordPress REST API
Connecting Content Silos: One CMS, Many Sites With The WordPress REST APICaldera Labs
 
Codeigniter : Two Step View - Concept Implementation
Codeigniter : Two Step View - Concept ImplementationCodeigniter : Two Step View - Concept Implementation
Codeigniter : Two Step View - Concept ImplementationAbdul Malik Ikhsan
 

Tendances (20)

Web Apps in Perl - HTTP 101
Web Apps in Perl - HTTP 101Web Apps in Perl - HTTP 101
Web Apps in Perl - HTTP 101
 
Mojolicious - Perl Framework for the Real-Time Web (Lightning Talk)
Mojolicious - Perl Framework for the Real-Time Web (Lightning Talk)Mojolicious - Perl Framework for the Real-Time Web (Lightning Talk)
Mojolicious - Perl Framework for the Real-Time Web (Lightning Talk)
 
Mojolicious. Веб в коробке!
Mojolicious. Веб в коробке!Mojolicious. Веб в коробке!
Mojolicious. Веб в коробке!
 
Webrtc mojo
Webrtc mojoWebrtc mojo
Webrtc mojo
 
Mojolicious, real-time web framework
Mojolicious, real-time web frameworkMojolicious, real-time web framework
Mojolicious, real-time web framework
 
Keeping it small - Getting to know the Slim PHP micro framework
Keeping it small - Getting to know the Slim PHP micro frameworkKeeping it small - Getting to know the Slim PHP micro framework
Keeping it small - Getting to know the Slim PHP micro framework
 
Blog Hacks 2011
Blog Hacks 2011Blog Hacks 2011
Blog Hacks 2011
 
YAPC::Asia 2010 Twitter解析サービス
YAPC::Asia 2010 Twitter解析サービスYAPC::Asia 2010 Twitter解析サービス
YAPC::Asia 2010 Twitter解析サービス
 
Slim RedBeanPHP and Knockout
Slim RedBeanPHP and KnockoutSlim RedBeanPHP and Knockout
Slim RedBeanPHP and Knockout
 
Keeping it small: Getting to know the Slim micro framework
Keeping it small: Getting to know the Slim micro frameworkKeeping it small: Getting to know the Slim micro framework
Keeping it small: Getting to know the Slim micro framework
 
Building Modern and Secure PHP Applications – Codementor Office Hours with Be...
Building Modern and Secure PHP Applications – Codementor Office Hours with Be...Building Modern and Secure PHP Applications – Codementor Office Hours with Be...
Building Modern and Secure PHP Applications – Codementor Office Hours with Be...
 
Keeping it Small: Getting to know the Slim Micro Framework
Keeping it Small: Getting to know the Slim Micro FrameworkKeeping it Small: Getting to know the Slim Micro Framework
Keeping it Small: Getting to know the Slim Micro Framework
 
エロサイト管理者の憂鬱3 - Hokkaiodo.pm#4 -
エロサイト管理者の憂鬱3 - Hokkaiodo.pm#4 -エロサイト管理者の憂鬱3 - Hokkaiodo.pm#4 -
エロサイト管理者の憂鬱3 - Hokkaiodo.pm#4 -
 
Twib in Yokoahma.pm 2010/3/5
Twib in Yokoahma.pm 2010/3/5Twib in Yokoahma.pm 2010/3/5
Twib in Yokoahma.pm 2010/3/5
 
Asynchronous programming patterns in Perl
Asynchronous programming patterns in PerlAsynchronous programming patterns in Perl
Asynchronous programming patterns in Perl
 
Extending the WordPress REST API - Josh Pollock
Extending the WordPress REST API - Josh PollockExtending the WordPress REST API - Josh Pollock
Extending the WordPress REST API - Josh Pollock
 
Using the new WordPress REST API
Using the new WordPress REST APIUsing the new WordPress REST API
Using the new WordPress REST API
 
PerlでWeb API入門
PerlでWeb API入門PerlでWeb API入門
PerlでWeb API入門
 
Connecting Content Silos: One CMS, Many Sites With The WordPress REST API
 Connecting Content Silos: One CMS, Many Sites With The WordPress REST API Connecting Content Silos: One CMS, Many Sites With The WordPress REST API
Connecting Content Silos: One CMS, Many Sites With The WordPress REST API
 
Codeigniter : Two Step View - Concept Implementation
Codeigniter : Two Step View - Concept ImplementationCodeigniter : Two Step View - Concept Implementation
Codeigniter : Two Step View - Concept Implementation
 

Similaire à RESTful web services

Doctrine For Beginners
Doctrine For BeginnersDoctrine For Beginners
Doctrine For BeginnersJonathan Wage
 
Perl Tools for Productivity
Perl Tools for ProductivityPerl Tools for Productivity
Perl Tools for ProductivityTudor Constantin
 
Bag Of Tricks From Iusethis
Bag Of Tricks From IusethisBag Of Tricks From Iusethis
Bag Of Tricks From IusethisMarcus Ramberg
 
Drupalcon 2023 - How Drupal builds your pages.pdf
Drupalcon 2023 - How Drupal builds your pages.pdfDrupalcon 2023 - How Drupal builds your pages.pdf
Drupalcon 2023 - How Drupal builds your pages.pdfLuca Lusso
 
2023 - Drupalcon - How Drupal builds your pages
2023 - Drupalcon - How Drupal builds your pages2023 - Drupalcon - How Drupal builds your pages
2023 - Drupalcon - How Drupal builds your pagessparkfabrik
 
Introducing Rendr: Run your Backbone.js apps on the client and server
Introducing Rendr: Run your Backbone.js apps on the client and serverIntroducing Rendr: Run your Backbone.js apps on the client and server
Introducing Rendr: Run your Backbone.js apps on the client and serverSpike Brehm
 
Web::Machine - Simpl{e,y} HTTP
Web::Machine - Simpl{e,y} HTTPWeb::Machine - Simpl{e,y} HTTP
Web::Machine - Simpl{e,y} HTTPMichael Francis
 
Laravel5 Introduction and essentials
Laravel5 Introduction and essentialsLaravel5 Introduction and essentials
Laravel5 Introduction and essentialsPramod Kadam
 
Services Drupalcamp Stockholm 2009
Services Drupalcamp Stockholm 2009Services Drupalcamp Stockholm 2009
Services Drupalcamp Stockholm 2009hugowetterberg
 
Symfony2 from the Trenches
Symfony2 from the TrenchesSymfony2 from the Trenches
Symfony2 from the TrenchesJonathan Wage
 
Rails 3 overview
Rails 3 overviewRails 3 overview
Rails 3 overviewYehuda Katz
 
I Phone On Rails
I Phone On RailsI Phone On Rails
I Phone On RailsJohn Wilker
 
Introduction to Backbone.js for Rails developers
Introduction to Backbone.js for Rails developersIntroduction to Backbone.js for Rails developers
Introduction to Backbone.js for Rails developersAoteaStudios
 
CodeIgniter PHP MVC Framework
CodeIgniter PHP MVC FrameworkCodeIgniter PHP MVC Framework
CodeIgniter PHP MVC FrameworkBo-Yi Wu
 
Symfony2 - from the trenches
Symfony2 - from the trenchesSymfony2 - from the trenches
Symfony2 - from the trenchesLukas Smith
 
Introduction to laravel framework
Introduction to laravel frameworkIntroduction to laravel framework
Introduction to laravel frameworkAhmad Fatoni
 
Curscatalyst
CurscatalystCurscatalyst
CurscatalystKar Juan
 

Similaire à RESTful web services (20)

Doctrine For Beginners
Doctrine For BeginnersDoctrine For Beginners
Doctrine For Beginners
 
Perl Tools for Productivity
Perl Tools for ProductivityPerl Tools for Productivity
Perl Tools for Productivity
 
Bag Of Tricks From Iusethis
Bag Of Tricks From IusethisBag Of Tricks From Iusethis
Bag Of Tricks From Iusethis
 
Basics of AngularJS
Basics of AngularJSBasics of AngularJS
Basics of AngularJS
 
Drupalcon 2023 - How Drupal builds your pages.pdf
Drupalcon 2023 - How Drupal builds your pages.pdfDrupalcon 2023 - How Drupal builds your pages.pdf
Drupalcon 2023 - How Drupal builds your pages.pdf
 
2023 - Drupalcon - How Drupal builds your pages
2023 - Drupalcon - How Drupal builds your pages2023 - Drupalcon - How Drupal builds your pages
2023 - Drupalcon - How Drupal builds your pages
 
Introducing Rendr: Run your Backbone.js apps on the client and server
Introducing Rendr: Run your Backbone.js apps on the client and serverIntroducing Rendr: Run your Backbone.js apps on the client and server
Introducing Rendr: Run your Backbone.js apps on the client and server
 
Web::Machine - Simpl{e,y} HTTP
Web::Machine - Simpl{e,y} HTTPWeb::Machine - Simpl{e,y} HTTP
Web::Machine - Simpl{e,y} HTTP
 
Laravel5 Introduction and essentials
Laravel5 Introduction and essentialsLaravel5 Introduction and essentials
Laravel5 Introduction and essentials
 
Services Drupalcamp Stockholm 2009
Services Drupalcamp Stockholm 2009Services Drupalcamp Stockholm 2009
Services Drupalcamp Stockholm 2009
 
Drupal 8 migrate!
Drupal 8 migrate!Drupal 8 migrate!
Drupal 8 migrate!
 
Symfony2 from the Trenches
Symfony2 from the TrenchesSymfony2 from the Trenches
Symfony2 from the Trenches
 
Rails 3 overview
Rails 3 overviewRails 3 overview
Rails 3 overview
 
I Phone On Rails
I Phone On RailsI Phone On Rails
I Phone On Rails
 
Introduction to Backbone.js for Rails developers
Introduction to Backbone.js for Rails developersIntroduction to Backbone.js for Rails developers
Introduction to Backbone.js for Rails developers
 
CodeIgniter PHP MVC Framework
CodeIgniter PHP MVC FrameworkCodeIgniter PHP MVC Framework
CodeIgniter PHP MVC Framework
 
Symfony2 - from the trenches
Symfony2 - from the trenchesSymfony2 - from the trenches
Symfony2 - from the trenches
 
Introduction to laravel framework
Introduction to laravel frameworkIntroduction to laravel framework
Introduction to laravel framework
 
Curscatalyst
CurscatalystCurscatalyst
Curscatalyst
 
Php summary
Php summaryPhp summary
Php summary
 

Dernier

Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsRavi Sanghani
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationKnoldus Inc.
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
Manual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditManual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditSkynet Technologies
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demoHarshalMandlekar2
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Alkin Tezuysal
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfNeo4j
 
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Scott Andery
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 

Dernier (20)

Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and Insights
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog Presentation
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
Manual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditManual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance Audit
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demo
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdf
 
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 

RESTful web services

  • 1. RESTful Web Services with Mojolicious and DBIx::Class
  • 2. About me ● Tudor Constantin ● Perl Developer @ Evozon ● http://programming.tudorconstantin.com/ ● http://stackoverflow.com/users/459233/tudor-constantin ● https://github.com/tudorconstantin ● http://www.linkedin.com/in/tudorconstantin ● twitter: @tudorconstantin ● gmail: tudorconstantin at gmail dot com
  • 3. Content ● Sample app overview - Expense Tracker ● (Short) Intro to RESTful Web Services ● DBIx::Class ● Mojolicious ● Routing in Mojo ● Generic Mojo Controller for CRUD operations ● Sample operation - update user ● Steps for getting RESTful routes/operations for a table in DB
  • 4. Sample app Expense Tracker VERY simple application - but usable (insert expenses, assign categories and see reports) ● Five tables ○ users ○ currencies ○ categories ○ operations ○ operations_categories ● Relationships ○ 1 user has many categories ○ 1 user has many operations ○ 1 category has many sub categories ○ 1 category has many operations ○ 1 operation has many categories ○ 1 operation has a currency 1 operation belongs to a user
  • 5. Intro to RESTful Web Services REST - REpresentational State Transfer ● concept introduced in 2000 by Roy Fielding in his academic dissertation, "Architectural Styles and the Design of Network-based Software Architectures" Main ideas for REST: ● Resources are accessible through unique URLs: ○ /user/23 ○ /operations ● Use HTTP methods explicitly ○ GET - for Read ○ POST - for Create ○ PUT - for Update ○ DELETE - for Delete ● Be stateless ○ the server does not know nor cares about the state of the client application ● Transfer Representations of resources (HTML, JSON, XML, etc)
  • 6. DBIx::Class ● An abstraction for working with DBs ● More than an ORM (Object Relational Mapper) - It knows how to work on Result Sets ● Components - simplified overview: ○ DBIx::Class::Schema - connection to DB ○ DBIx::Class::ResultSet - a query used for fetching a set of results ○ DBIx::Class::Row - objects returned from DBIx::Class::ResultSets using the create, find, next and all methods ● Sample usage: my @rows = ExpenseTracker::Models->connect( $config->{database}->{ $mode }->{dsn}, $config->{database}->{ $mode }->{user}, $config->{database}->{ $mode }->{password}, ) # DBIx::Class::Schema ->resultset( 'ExpenseTracker::Models::Result::User' ) # DBIx::Class::ResultSet ->search_rs( { id => 10 }, ) # DBIx::Class::ResultSet - only users with id = 10 ->all(); # The collection of DBIx::Class::Row instances
  • 7. Mojolicious ● Microframework inspired by Sinatra (Ruby) ● Components of interest (for this app) ○ Router ○ Controller ● Not (quite) interested in: ○ Views (since we render mainly json) ● Not provided at all: ○ Models (we plug in and use DBIx::Class)
  • 8. Routing in Mojolicious In app context (ie - the startup routine): my $r = $self->routes; #sample route named 'login' for GET - executing method login from controller ExpenseTracker::Controllers::Login $r->get('/login')->to('login#login')->name('login'); Shortcut, generic routing: $params->{app_routes}->add_shortcut(resource => sub { my ($r, $name ) = @_; # Generate route for "/$name" - Controller is ExpenseTracker::Controller::camelize($name) my $resource = $r->route( "/$name" )->to("$name#"); # Handle POST requests - will hit the create method in controller $resource->post->to('#create')->name("create_$name"); # Handle GET requests - lists the collection of this resource - hits the list method in controller $resource->get->to('#list')->name("list_$name"); $resource = $r->route( "/$name/:id" )->to("$name#"); $resource->get->to('#show')->name("show_$name"); $resource->delete->to('#remove')->name("delete_$name"); $resource->put->to('#update')->name("update_$name"); return $resource; });
  • 9. Generic Controller for CRUD Operations ● Each resource needs a controller responsible for it ● Each of those controllers will have to implement at least 7 actions: ○ create - POST /resource_name - creates a new resource ○ update - PUT /resource_name/:id - updates a resource ○ list - GET /resource_name - show the collection of resources ○ show - GET /resource_name/:id - get the resource with id :id ○ remove - DELETE /resource_name/:id - annihilate resource :id ● Possible approaches ○ create a Moose role that will expose all those methods and use this role (I guess) ○ implement a basic controller that will be inherited by all the other resource controller
  • 10. Sample op - update user In child controller (ExpenseTracker::Controller::User) =head update sample of overriding a default update method route here: PUT /user/:id =cut sub update{ my $self = shift; return $self->render(status => 405, json => {message => 'You can only update your own profile!!!'} ) if ( !defined $self->param('id') or !defined $self->app->user or $self->param('id') != $self->app->user->id ); return $self->SUPER::update(@_); }
  • 11. Sample op - update user In base controller ExpenseTracker::Controllers::Base - the one that ExpenseTracker::Controllers::User inherits from: sub update{ my $self = shift; my $result_rs = $self->app->model ->resultset( $self->{resource} ) ->search_rs( { id => $self->param('id') }, ); return $self->render_not_found if ( scalar( ( $result_rs->all ) ) == 0 ); $result_rs->update_all( $self->req->json ); $result_rs->result_class('DBIx::Class::ResultClass::HashRefInflator'); my @result = $result_rs->all(); return $self->render_json( [ @result ] ); }
  • 12. Steps for getting RESTful routes/operations ● Generate the DBIx::Class model based on the DB table, with DBIx:: Class::Schema::Loader ● Create a controller that inherits from ExpenseTracker::Controllers::Base ● Add the resource name to the conf.yml
  • 13. The End Fork the sample app and play with it: https://github.com/tudorconstantin/expense-tracker