SlideShare a Scribd company logo
FLASK RESTLESS
FAST AND EASY REST API’S
Code Samples
Github

https://github.com/mandshaw/
flask_microbrewery
What is Flask Restless
Library built around flask

Model driven

Define your models

Define their relationships

Expose your models

Specify what to expose them on (GET, POST,
PUT, DELETE
What is Flask Restless
Uses SQLAlchemy

Supports SQLite, Postgresql, MySQL, Oracle
and many more

Built in query language (FOR FREE!)
Models
What is a model?

Comes from SQLAlchemy or Flask-SQLAlchemy

Used to represent objects which will become
records in a database
Flask-SQLAlchemy
Abstracts away a lot of unnecessary SQLAlchemy
config and makes your life easier. 

Read more here
Defining a Model
# Define the models

class Beer(db.Model):

id = db.Column(db.Integer, primary_key=True)

name = db.Column(db.Unicode, unique=True)
Will execute:
CREATE TABLE beer (

	 id INTEGER NOT NULL, 

	 name VARCHAR, 

	 PRIMARY KEY (id), 

	 UNIQUE (name), 

)
Turning a Model into a API
# Create the DB

db.create_all()



# Create the Flask-Restless API manager.

manager = APIManager(app, flask_sqlalchemy_db=db)



# Create the API endpoints from the DB Models

# These will be available at /api/<tablename>

manager.create_api(Beer, methods=['GET', 'POST', 'PUT',
'DELETE'])
DEMO STEP/1
Relationships
Creating a one to many
Relationship
Relationship always goes on the ‘one’ side 

# Define the models

class Beer(db.Model):

id = db.Column(db.Integer, primary_key=True)

name = db.Column(db.Unicode, unique=True)
# Create a foreign key

type_id = db.Column(db.Integer, db.ForeignKey(‘type.id’))




class Type(db.Model):

id = db.Column(db.Integer, primary_key=True)

name = db.Column(db.Unicode, unique=True)
# Create a relationship

beers = db.relationship('Beer', backref=db.backref('type'), lazy=‘dynamic')
DEMO STEP/2
Making Fields Invisible
Excluding Columns
You can use exclude_columns or include_columns
to hide columns in the response

manager.create_api(Beer, methods=['GET', 'POST', 'PUT',
'DELETE'], exclude_columns=['reviews', 'type'])

DEMO STEP/3
Pre and Post Processing
Consider
On a POST or PUT for a review you want to add
the date that the review was created

Do you?

Do this client side (What time zone? What
format)

Do this server side
Processors
# Augments the request with the current db DATETIMESTAMP
# When submitted
def add_current_date(**kw):

kw['data']['date'] = 'CURRENT_TIMESTAMP'

return kw



# Create the API endpoints from the DB Models

# These will be available at /api/<tablename>
manager.create_api(

Review,

methods=['GET', 'POST', 'PUT', 'DELETE'],

preprocessors = {

'POST': [add_current_date],

'PUT_SINGLE': [add_current_date]

}

)
Processors
Preprocessors -> before the requests is processed

Postprocessors -> before the response is returned
DEMO STEP/4
Validation
Validation
Not performed by Flask-Restless

Roll your own or use a combination of the
SQLAlchemy validate decorator and flasks abort
Validation
from flask import Flask, abort
from sqlalchemy.orm import validates
class Review(db.Model):

id = db.Column(db.Integer, primary_key=True)

date = db.Column(db.DateTime)

stars = db.Column(db.Integer)

comment = db.Column(db.Unicode)

beer_id = db.Column(db.Integer, db.ForeignKey('beer.id'))

author_id = db.Column(db.Integer, db.ForeignKey('reviewer.id'))



@validates('stars')

def validate_name(self, key, stars):

if stars >= 1 and stars <=5:

return stars

else:

return abort(400, description='A review must have a star
rating of between 1 and 5')
Pagination
Server side Pagination
Natively uses server side pagination (default is 10
results per page)

<host>/api/<resource>?page=2 Give you page 2

Set the results_per_page attribute when creating
your api to over-ride



manager.create_api(Reviewer, methods=['GET', 'POST',
'PUT', 'DELETE'], results_per_page=2)
Querying data
NULL is the Chuck Norris of the database.
Nothing can be compared to it. - Unknown
Querying Data
Support query params on GETS

Uses Query Filters

<host>/api/<resource>/?q={“filter”:[…filters…]}
Query Filters
Lists of 

{“name”: name, “op”: op, “val”: val}

{“name”: name, “op”: op, “field”: field}
name The field to use
op The operator to use
val The Value to use
field The field to compare name to
Valid Operators
equal ==, eq, equals, equals_to
not equal !=, neq, does_not_equal, not_equal_to
comparison >, gt, <, lt, >=, ge, gte, geq, <=, le, lte, leq
membership in, not_in
null check is_null, is_not_null
like like
has has
any any
Querying Data
Extremely feature rich

Order by

Group By

Single result expected

READ THE DOCS
Examples
Get all the Hipsters

GET localhost:5000/api/reviewer?q={"filters":
[{"name":"name","op": "ilike", "val":"Hipster%"}]}
Reviews with more than 3 stars

GET localhost:5000/api/review?q={"filters":
[{"name":"stars","op": "gt", "val":3}]}
All reviews made by Hipster Jane

GET localhost:5000/api/review?q={"filters":
[{"name":"author","op":"has","val":{"name":"name",
"op":"eq", "val":"Hipster Jane”}}]}
Examples
You can also use relationships in a GET

All reviews made by Hipster Jane(id=2)

GET localhost:5000/api/reviewer/2/
reviews
Further Reading
You can use SQLAlchemy migrate to migrate you
DB revisions

Read all about it (and lots more) here
QUESTIONS?

More Related Content

What's hot (20)

PPTX
Introduction to laravel framework
Ahmad Fatoni
 
PDF
Activator and Reactive at Play NYC meetup
Henrik Engström
 
PDF
Java Server Faces
Mario Jorge Pereira
 
PPT
Presentation
Manav Prasad
 
PPTX
SQL Injection Defense in Python
Public Broadcasting Service
 
PDF
Revolution or Evolution in Page Object
Artem Sokovets
 
PPT
Selenium
husnara mohammad
 
PPT
Web service with Laravel
Abuzer Firdousi
 
PDF
Doing Drupal security right
Gábor Hojtsy
 
KEY
Action Controller Overview, Season 1
RORLAB
 
PPTX
Introduction to ElasticSearch
Simobo
 
PPT
Devoxx UK 2015: How Java EE has changed pattern implementation
Alex Theedom
 
PDF
Sql Injection Myths and Fallacies
Karwin Software Solutions LLC
 
PDF
Web services with laravel
Confiz
 
PPTX
SQL Injection in action with PHP and MySQL
Pradeep Kumar
 
PDF
Laravel Restful API and AngularJS
Blake Newman
 
PDF
Advancing JavaScript with Libraries (Yahoo Tech Talk)
jeresig
 
PPTX
Laravel - Website Development in Php Framework.
SWAAM Tech
 
PPTX
Spring Introduction
Cao Manh Dat
 
PPTX
Laravel ppt
Mayank Panchal
 
Introduction to laravel framework
Ahmad Fatoni
 
Activator and Reactive at Play NYC meetup
Henrik Engström
 
Java Server Faces
Mario Jorge Pereira
 
Presentation
Manav Prasad
 
SQL Injection Defense in Python
Public Broadcasting Service
 
Revolution or Evolution in Page Object
Artem Sokovets
 
Web service with Laravel
Abuzer Firdousi
 
Doing Drupal security right
Gábor Hojtsy
 
Action Controller Overview, Season 1
RORLAB
 
Introduction to ElasticSearch
Simobo
 
Devoxx UK 2015: How Java EE has changed pattern implementation
Alex Theedom
 
Sql Injection Myths and Fallacies
Karwin Software Solutions LLC
 
Web services with laravel
Confiz
 
SQL Injection in action with PHP and MySQL
Pradeep Kumar
 
Laravel Restful API and AngularJS
Blake Newman
 
Advancing JavaScript with Libraries (Yahoo Tech Talk)
jeresig
 
Laravel - Website Development in Php Framework.
SWAAM Tech
 
Spring Introduction
Cao Manh Dat
 
Laravel ppt
Mayank Panchal
 

Similar to Flask restless (20)

PDF
Php summary
Michelle Darling
 
PDF
Get database properties using power shell in sql server 2008 techrepublic
Kaing Menglieng
 
PPTX
php2.pptx
ElieNGOMSEU
 
PPTX
Flask & Flask-restx
ammaraslam18
 
PDF
Getting to know Laravel 5
Bukhori Aqid
 
PDF
Intro to Laravel 4
Singapore PHP User Group
 
PDF
Frameworks da nova Era PHP FuelPHP
Dan Jesus
 
PDF
SQL Injection: complete walkthrough (not only) for PHP developers
Krzysztof Kotowicz
 
PDF
Um roadmap do Framework Ruby on Rails, do Rails 1 ao Rails 4 - DevDay 2013
Joao Lucas Santana
 
PPT
13 java in oracle
Graham Royce
 
PDF
Scala active record
鉄平 土佐
 
PDF
Fast Web Applications Development with Ruby on Rails on Oracle
Raimonds Simanovskis
 
PDF
OWASP Top 10 at International PHP Conference 2014 in Berlin
Tobias Zander
 
PDF
Solid and Sustainable Development in Scala
scalaconfjp
 
PDF
Solid And Sustainable Development in Scala
Kazuhiro Sera
 
PPT
plsql les06
sasa_eldoby
 
PDF
Defcon_Oracle_The_Making_of_the_2nd_sql_injection_worm
guest785f78
 
PPTX
Playing With (B)Sqli
Chema Alonso
 
PPTX
Laravel for Web Artisans
Raf Kewl
 
KEY
Building and Distributing PostgreSQL Extensions Without Learning C
David Wheeler
 
Php summary
Michelle Darling
 
Get database properties using power shell in sql server 2008 techrepublic
Kaing Menglieng
 
php2.pptx
ElieNGOMSEU
 
Flask & Flask-restx
ammaraslam18
 
Getting to know Laravel 5
Bukhori Aqid
 
Intro to Laravel 4
Singapore PHP User Group
 
Frameworks da nova Era PHP FuelPHP
Dan Jesus
 
SQL Injection: complete walkthrough (not only) for PHP developers
Krzysztof Kotowicz
 
Um roadmap do Framework Ruby on Rails, do Rails 1 ao Rails 4 - DevDay 2013
Joao Lucas Santana
 
13 java in oracle
Graham Royce
 
Scala active record
鉄平 土佐
 
Fast Web Applications Development with Ruby on Rails on Oracle
Raimonds Simanovskis
 
OWASP Top 10 at International PHP Conference 2014 in Berlin
Tobias Zander
 
Solid and Sustainable Development in Scala
scalaconfjp
 
Solid And Sustainable Development in Scala
Kazuhiro Sera
 
plsql les06
sasa_eldoby
 
Defcon_Oracle_The_Making_of_the_2nd_sql_injection_worm
guest785f78
 
Playing With (B)Sqli
Chema Alonso
 
Laravel for Web Artisans
Raf Kewl
 
Building and Distributing PostgreSQL Extensions Without Learning C
David Wheeler
 
Ad

Recently uploaded (20)

PDF
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
PDF
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
PDF
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
PDF
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
PDF
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
PDF
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
PPTX
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
PDF
DevBcn - Building 10x Organizations Using Modern Productivity Metrics
Justin Reock
 
PPTX
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 
PPTX
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 
PDF
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
PDF
What Makes Contify’s News API Stand Out: Key Features at a Glance
Contify
 
PDF
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
PDF
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 
PPTX
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
PDF
Chris Elwell Woburn, MA - Passionate About IT Innovation
Chris Elwell Woburn, MA
 
PDF
Blockchain Transactions Explained For Everyone
CIFDAQ
 
PDF
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
PDF
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
PDF
HCIP-Data Center Facility Deployment V2.0 Training Material (Without Remarks ...
mcastillo49
 
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
DevBcn - Building 10x Organizations Using Modern Productivity Metrics
Justin Reock
 
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
What Makes Contify’s News API Stand Out: Key Features at a Glance
Contify
 
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
Chris Elwell Woburn, MA - Passionate About IT Innovation
Chris Elwell Woburn, MA
 
Blockchain Transactions Explained For Everyone
CIFDAQ
 
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
HCIP-Data Center Facility Deployment V2.0 Training Material (Without Remarks ...
mcastillo49
 
Ad

Flask restless

  • 1. FLASK RESTLESS FAST AND EASY REST API’S
  • 3. What is Flask Restless Library built around flask Model driven Define your models Define their relationships Expose your models Specify what to expose them on (GET, POST, PUT, DELETE
  • 4. What is Flask Restless Uses SQLAlchemy Supports SQLite, Postgresql, MySQL, Oracle and many more Built in query language (FOR FREE!)
  • 5. Models What is a model? Comes from SQLAlchemy or Flask-SQLAlchemy Used to represent objects which will become records in a database
  • 6. Flask-SQLAlchemy Abstracts away a lot of unnecessary SQLAlchemy config and makes your life easier. Read more here
  • 7. Defining a Model # Define the models
 class Beer(db.Model):
 id = db.Column(db.Integer, primary_key=True)
 name = db.Column(db.Unicode, unique=True) Will execute: CREATE TABLE beer ( id INTEGER NOT NULL, name VARCHAR, PRIMARY KEY (id), UNIQUE (name), )
  • 8. Turning a Model into a API # Create the DB
 db.create_all()
 
 # Create the Flask-Restless API manager.
 manager = APIManager(app, flask_sqlalchemy_db=db)
 
 # Create the API endpoints from the DB Models
 # These will be available at /api/<tablename>
 manager.create_api(Beer, methods=['GET', 'POST', 'PUT', 'DELETE'])
  • 11. Creating a one to many Relationship Relationship always goes on the ‘one’ side # Define the models
 class Beer(db.Model):
 id = db.Column(db.Integer, primary_key=True)
 name = db.Column(db.Unicode, unique=True) # Create a foreign key
 type_id = db.Column(db.Integer, db.ForeignKey(‘type.id’)) 
 
 class Type(db.Model):
 id = db.Column(db.Integer, primary_key=True)
 name = db.Column(db.Unicode, unique=True) # Create a relationship
 beers = db.relationship('Beer', backref=db.backref('type'), lazy=‘dynamic')
  • 14. Excluding Columns You can use exclude_columns or include_columns to hide columns in the response manager.create_api(Beer, methods=['GET', 'POST', 'PUT', 'DELETE'], exclude_columns=['reviews', 'type'])

  • 16. Pre and Post Processing
  • 17. Consider On a POST or PUT for a review you want to add the date that the review was created Do you? Do this client side (What time zone? What format) Do this server side
  • 18. Processors # Augments the request with the current db DATETIMESTAMP # When submitted def add_current_date(**kw):
 kw['data']['date'] = 'CURRENT_TIMESTAMP'
 return kw
 
 # Create the API endpoints from the DB Models
 # These will be available at /api/<tablename> manager.create_api(
 Review,
 methods=['GET', 'POST', 'PUT', 'DELETE'],
 preprocessors = {
 'POST': [add_current_date],
 'PUT_SINGLE': [add_current_date]
 }
 )
  • 19. Processors Preprocessors -> before the requests is processed Postprocessors -> before the response is returned
  • 22. Validation Not performed by Flask-Restless Roll your own or use a combination of the SQLAlchemy validate decorator and flasks abort
  • 23. Validation from flask import Flask, abort from sqlalchemy.orm import validates class Review(db.Model):
 id = db.Column(db.Integer, primary_key=True)
 date = db.Column(db.DateTime)
 stars = db.Column(db.Integer)
 comment = db.Column(db.Unicode)
 beer_id = db.Column(db.Integer, db.ForeignKey('beer.id'))
 author_id = db.Column(db.Integer, db.ForeignKey('reviewer.id'))
 
 @validates('stars')
 def validate_name(self, key, stars):
 if stars >= 1 and stars <=5:
 return stars
 else:
 return abort(400, description='A review must have a star rating of between 1 and 5')
  • 25. Server side Pagination Natively uses server side pagination (default is 10 results per page) <host>/api/<resource>?page=2 Give you page 2 Set the results_per_page attribute when creating your api to over-ride 
 manager.create_api(Reviewer, methods=['GET', 'POST', 'PUT', 'DELETE'], results_per_page=2)
  • 26. Querying data NULL is the Chuck Norris of the database. Nothing can be compared to it. - Unknown
  • 27. Querying Data Support query params on GETS Uses Query Filters <host>/api/<resource>/?q={“filter”:[…filters…]}
  • 28. Query Filters Lists of {“name”: name, “op”: op, “val”: val} {“name”: name, “op”: op, “field”: field} name The field to use op The operator to use val The Value to use field The field to compare name to
  • 29. Valid Operators equal ==, eq, equals, equals_to not equal !=, neq, does_not_equal, not_equal_to comparison >, gt, <, lt, >=, ge, gte, geq, <=, le, lte, leq membership in, not_in null check is_null, is_not_null like like has has any any
  • 30. Querying Data Extremely feature rich Order by Group By Single result expected READ THE DOCS
  • 31. Examples Get all the Hipsters GET localhost:5000/api/reviewer?q={"filters": [{"name":"name","op": "ilike", "val":"Hipster%"}]} Reviews with more than 3 stars GET localhost:5000/api/review?q={"filters": [{"name":"stars","op": "gt", "val":3}]} All reviews made by Hipster Jane GET localhost:5000/api/review?q={"filters": [{"name":"author","op":"has","val":{"name":"name", "op":"eq", "val":"Hipster Jane”}}]}
  • 32. Examples You can also use relationships in a GET All reviews made by Hipster Jane(id=2) GET localhost:5000/api/reviewer/2/ reviews
  • 33. Further Reading You can use SQLAlchemy migrate to migrate you DB revisions Read all about it (and lots more) here