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

PPTX
Scaladays 2014 introduction to scalatest selenium dsl
PDF
เกี่ยวกับ Apache solr 4.0
PDF
Efficient Rails Test Driven Development (class 4) by Wolfram Arnold
PPT
PDF
Efficient Rails Test-Driven Development - Week 6
PDF
Efficient Rails Test Driven Development (class 3) by Wolfram Arnold
PPTX
Softshake 2013: 10 reasons why java developers are jealous of Scala developers
PPT
Intro to-ant
Scaladays 2014 introduction to scalatest selenium dsl
เกี่ยวกับ Apache solr 4.0
Efficient Rails Test Driven Development (class 4) by Wolfram Arnold
Efficient Rails Test-Driven Development - Week 6
Efficient Rails Test Driven Development (class 3) by Wolfram Arnold
Softshake 2013: 10 reasons why java developers are jealous of Scala developers
Intro to-ant

What's hot (20)

PPTX
Introduction to laravel framework
PDF
Activator and Reactive at Play NYC meetup
PDF
Java Server Faces
PPT
Presentation
PPTX
SQL Injection Defense in Python
PDF
Revolution or Evolution in Page Object
PPT
PPT
Web service with Laravel
PDF
Doing Drupal security right
KEY
Action Controller Overview, Season 1
PPTX
Introduction to ElasticSearch
PPT
Devoxx UK 2015: How Java EE has changed pattern implementation
PDF
Sql Injection Myths and Fallacies
PDF
Web services with laravel
PPTX
SQL Injection in action with PHP and MySQL
PDF
Laravel Restful API and AngularJS
PDF
Advancing JavaScript with Libraries (Yahoo Tech Talk)
PPTX
Laravel - Website Development in Php Framework.
PPTX
Spring Introduction
PPTX
Laravel ppt
Introduction to laravel framework
Activator and Reactive at Play NYC meetup
Java Server Faces
Presentation
SQL Injection Defense in Python
Revolution or Evolution in Page Object
Web service with Laravel
Doing Drupal security right
Action Controller Overview, Season 1
Introduction to ElasticSearch
Devoxx UK 2015: How Java EE has changed pattern implementation
Sql Injection Myths and Fallacies
Web services with laravel
SQL Injection in action with PHP and MySQL
Laravel Restful API and AngularJS
Advancing JavaScript with Libraries (Yahoo Tech Talk)
Laravel - Website Development in Php Framework.
Spring Introduction
Laravel ppt
Ad

Similar to Flask restless (20)

PPTX
Build restful ap is with python and flask
PDF
Rest API using Flask & SqlAlchemy
PDF
Python RESTful webservices with Python: Flask and Django solutions
PDF
FastAPI - Rest Architecture - in english.pdf
PDF
Introduction to Flask Micro Framework
PPTX
Flask & Flask-restx
PDF
Flask patterns
ODP
Intravert Server side processing for Cassandra
ODP
NYC* 2013 - "Advanced Data Processing: Beyond Queries and Slices"
PDF
Enhance Your Flask Web Project With a Database Python Guide.pdf
PDF
Scaling tappsi
PPTX
Flask-RESTPlusで便利なREST API開発 | Productive RESTful API development with Flask-...
PDF
Enterprise-Ready FastAPI: Beyond the Basics
PDF
PPTX
PostgREST Design Philosophy
PDF
Challenges when building high profile editorial sites
PPTX
Flask Application ppt to understand the flask
PPT
Google App Engine
PPTX
SW Security Lec4 Securing architecture.pptx
PDF
Memcached Code Camp 2009
Build restful ap is with python and flask
Rest API using Flask & SqlAlchemy
Python RESTful webservices with Python: Flask and Django solutions
FastAPI - Rest Architecture - in english.pdf
Introduction to Flask Micro Framework
Flask & Flask-restx
Flask patterns
Intravert Server side processing for Cassandra
NYC* 2013 - "Advanced Data Processing: Beyond Queries and Slices"
Enhance Your Flask Web Project With a Database Python Guide.pdf
Scaling tappsi
Flask-RESTPlusで便利なREST API開発 | Productive RESTful API development with Flask-...
Enterprise-Ready FastAPI: Beyond the Basics
PostgREST Design Philosophy
Challenges when building high profile editorial sites
Flask Application ppt to understand the flask
Google App Engine
SW Security Lec4 Securing architecture.pptx
Memcached Code Camp 2009
Ad

Recently uploaded (20)

PDF
Electronic commerce courselecture one. Pdf
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PPTX
Cloud computing and distributed systems.
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
cuic standard and advanced reporting.pdf
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PDF
Encapsulation theory and applications.pdf
DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PPTX
MYSQL Presentation for SQL database connectivity
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PPTX
Big Data Technologies - Introduction.pptx
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
Empathic Computing: Creating Shared Understanding
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
Machine learning based COVID-19 study performance prediction
PDF
Network Security Unit 5.pdf for BCA BBA.
Electronic commerce courselecture one. Pdf
Diabetes mellitus diagnosis method based random forest with bat algorithm
Cloud computing and distributed systems.
Building Integrated photovoltaic BIPV_UPV.pdf
cuic standard and advanced reporting.pdf
Understanding_Digital_Forensics_Presentation.pptx
Encapsulation theory and applications.pdf
The AUB Centre for AI in Media Proposal.docx
Dropbox Q2 2025 Financial Results & Investor Presentation
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
MYSQL Presentation for SQL database connectivity
Unlocking AI with Model Context Protocol (MCP)
NewMind AI Weekly Chronicles - August'25 Week I
Big Data Technologies - Introduction.pptx
Review of recent advances in non-invasive hemoglobin estimation
Empathic Computing: Creating Shared Understanding
Reach Out and Touch Someone: Haptics and Empathic Computing
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Machine learning based COVID-19 study performance prediction
Network Security Unit 5.pdf for BCA BBA.

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