SlideShare a Scribd company logo
FLASK & FLASK
RESTX
An Introduction
Basic FLASK Application
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello_world():
return "<p>Hello, World!</p>"
@app.route('/user/<username>')
def profile(username):
return f"{username}'s profile"
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
return do_the_login()
else:
return show_the_login_form()
To run the application: flask run
The URL / will run
this function
The URL
/username/test will
run this function
The URL /login will
run this function
Useful Functions
Get url of a static file:
url_for('static', filename='style.css')
Render html page:
return render_template('hello.html', variable="value")
Redirect:
redirect(url_for('login'))
Abort:
abort(401)
The request object allows you to access useful properties, such as request.args
(URL args), request.form, request.files and request.method. You can also get
cookies through the request object i.e.
request.cookies.get('username')
from flask import session
session['username'] = "hello"
print(session['username'])
Global error handlers
You can add global error handlers for specific exceptions or errors
@app.errorhandler(404)
def page_not_found(error):
return render_template('page_not_found.html'), 404
from flask import jsonify
@app.route("/users")def users_api():
users = get_all_users()
return jsonify([user.to_json() for user in users])
Apis – Support for JSON
Flask-Sqlalchemy (Database)
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI’] = 'sqlite:////tmp/db.db'
db = SQLAlchemy(app)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True)
email = db.Column(db.String(120), unique=True)
class Post(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(80), nullable=False)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
user = db.relationship('User', backref=db.backref('posts',
lazy=True))
The advantage of making relationships is the ability to directly get rows of related table
effortlessly i.e. print(post.user.username)
Flask-restx
Flask restx is a fork of flask-restplus, it was made because the original
library isn’t actively maintained.
Flask-restx provides built-in support for Swagger 2.0, which will
automatically provide documentation for endpoints and models. You can
also test the api’s using a doc URL, without the need for Postman.
Flask-restx comes with decorators that allow programmers to handle
what input’s will be allowed of what types, without writing any logic. The
responses are also controlled, extra fields can be automatically removed.
Moreover, if you return objects, they’re automatically jsonified.
Example setup
from flask import Flask
from flask_restx import Api
app = Flask(__name__)
api = Api(app)
@api.route('/hello')
class HelloWorld(Resource):
def get(self):
return {'hello': 'world'}
Notice that the function is named “get” which corresponds to the request
type.
Expect & Marshal With
model = api.model('Model’, {
'task': fields.String,
'uri': fields.Url('todo_ep’)
})
model2 = api.model('Model’, {
'name': fields.String(required=True),
}, strict=True)
class Todo(Resource):
@api.expect(model2)
@api.marshal_with(model, skip_none=True)
def post(self, **kwargs):
return TodoDao(todo_id='my_todo', task='Remember’)
@api.expect controls the input, strict means no extra fields are allowed, and
required means that the api will fail without the input. You can also do regex
pattern matching in the model
@api.marshal_with controls the output, Notice that the an object is being
returned
Sample Project Structure
- api
- user
- __init__.py
- schema.py
- endpoint.py
- model
- user.py

More Related Content

DOCX
Packet Tracer: WAN, point to point links.
PDF
Demystifying blockchain
PPTX
Memory access tracing [poug17]
PPTX
OAuth in the Wild
PPTX
Blockchain+IOT
PDF
Secure Spring Boot Microservices with Keycloak
PDF
Eclipse - Installation and quick start guide
PPTX
Linux memory-management-kamal
Packet Tracer: WAN, point to point links.
Demystifying blockchain
Memory access tracing [poug17]
OAuth in the Wild
Blockchain+IOT
Secure Spring Boot Microservices with Keycloak
Eclipse - Installation and quick start guide
Linux memory-management-kamal

What's hot (20)

POTX
Performance Tuning EC2 Instances
PDF
Decentralized Application: A Software Engineering Perspective
DOCX
Data power Performance Tuning
PDF
Blockchain Study(1) - What is Blockchain?
PPTX
Camunda in Action
PDF
Blockchain Training | Blockchain Tutorial for Beginners | Blockchain Technolo...
PDF
Socket programming
ODP
Hyperledger Fabric and Tools
PDF
Linux Systems Performance 2016
PDF
Xampp Workshop
PPTX
API Design- Best Practices
PPTX
Getting started with Octopus Deploy
KEY
Intro to Erlang
PPTX
Blockchain for Business
PPT
Basic Linux Internals
PDF
Denver MuleSoft Meetup: Deep Dive into Anypoint Runtime Fabric Security
DOCX
Poll mode driver integration into dpdk
PPTX
Block chain technology
PDF
Introduction to Apache ActiveMQ Artemis
Performance Tuning EC2 Instances
Decentralized Application: A Software Engineering Perspective
Data power Performance Tuning
Blockchain Study(1) - What is Blockchain?
Camunda in Action
Blockchain Training | Blockchain Tutorial for Beginners | Blockchain Technolo...
Socket programming
Hyperledger Fabric and Tools
Linux Systems Performance 2016
Xampp Workshop
API Design- Best Practices
Getting started with Octopus Deploy
Intro to Erlang
Blockchain for Business
Basic Linux Internals
Denver MuleSoft Meetup: Deep Dive into Anypoint Runtime Fabric Security
Poll mode driver integration into dpdk
Block chain technology
Introduction to Apache ActiveMQ Artemis
Ad

Similar to Flask & Flask-restx (20)

PPTX
Flask-Python
PPTX
Flask-RESTPlusで便利なREST API開発 | Productive RESTful API development with Flask-...
PDF
Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...
PPTX
SW Security Lec4 Securing architecture.pptx
PDF
Flask patterns
PPTX
Flask Application ppt to understand the flask
PDF
Flask - Backend com Python - Semcomp 18
KEY
LvivPy - Flask in details
PPTX
Build restful ap is with python and flask
PDF
Frameworks da nova Era PHP FuelPHP
PPT
Corba
PDF
URLProtocol
PDF
Flask Introduction - Python Meetup
PDF
Bootstrat REST APIs with Laravel 5
PDF
Flask and Angular: An approach to build robust platforms
PDF
Java Libraries You Can’t Afford to Miss
PPTX
Laravel for Web Artisans
PDF
Denys Serhiienko "ASGI in depth"
PDF
Practical Celery
KEY
PyCon US 2012 - State of WSGI 2
Flask-Python
Flask-RESTPlusで便利なREST API開発 | Productive RESTful API development with Flask-...
Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...
SW Security Lec4 Securing architecture.pptx
Flask patterns
Flask Application ppt to understand the flask
Flask - Backend com Python - Semcomp 18
LvivPy - Flask in details
Build restful ap is with python and flask
Frameworks da nova Era PHP FuelPHP
Corba
URLProtocol
Flask Introduction - Python Meetup
Bootstrat REST APIs with Laravel 5
Flask and Angular: An approach to build robust platforms
Java Libraries You Can’t Afford to Miss
Laravel for Web Artisans
Denys Serhiienko "ASGI in depth"
Practical Celery
PyCon US 2012 - State of WSGI 2
Ad

Recently uploaded (20)

PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
KodekX | Application Modernization Development
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PPTX
Cloud computing and distributed systems.
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
cuic standard and advanced reporting.pdf
PPTX
Programs and apps: productivity, graphics, security and other tools
PDF
Encapsulation theory and applications.pdf
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
20250228 LYD VKU AI Blended-Learning.pptx
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
The AUB Centre for AI in Media Proposal.docx
KodekX | Application Modernization Development
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
Cloud computing and distributed systems.
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Review of recent advances in non-invasive hemoglobin estimation
cuic standard and advanced reporting.pdf
Programs and apps: productivity, graphics, security and other tools
Encapsulation theory and applications.pdf
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
Understanding_Digital_Forensics_Presentation.pptx
NewMind AI Weekly Chronicles - August'25 Week I
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Dropbox Q2 2025 Financial Results & Investor Presentation
Digital-Transformation-Roadmap-for-Companies.pptx
The Rise and Fall of 3GPP – Time for a Sabbatical?
Reach Out and Touch Someone: Haptics and Empathic Computing

Flask & Flask-restx

  • 1. FLASK & FLASK RESTX An Introduction
  • 2. Basic FLASK Application from flask import Flask app = Flask(__name__) @app.route("/") def hello_world(): return "<p>Hello, World!</p>" @app.route('/user/<username>') def profile(username): return f"{username}'s profile" @app.route('/login', methods=['GET', 'POST']) def login(): if request.method == 'POST': return do_the_login() else: return show_the_login_form() To run the application: flask run The URL / will run this function The URL /username/test will run this function The URL /login will run this function
  • 3. Useful Functions Get url of a static file: url_for('static', filename='style.css') Render html page: return render_template('hello.html', variable="value") Redirect: redirect(url_for('login')) Abort: abort(401) The request object allows you to access useful properties, such as request.args (URL args), request.form, request.files and request.method. You can also get cookies through the request object i.e. request.cookies.get('username') from flask import session session['username'] = "hello" print(session['username'])
  • 4. Global error handlers You can add global error handlers for specific exceptions or errors @app.errorhandler(404) def page_not_found(error): return render_template('page_not_found.html'), 404 from flask import jsonify @app.route("/users")def users_api(): users = get_all_users() return jsonify([user.to_json() for user in users]) Apis – Support for JSON
  • 5. Flask-Sqlalchemy (Database) app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI’] = 'sqlite:////tmp/db.db' db = SQLAlchemy(app) class User(db.Model): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(80), unique=True) email = db.Column(db.String(120), unique=True) class Post(db.Model): id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(80), nullable=False) user_id = db.Column(db.Integer, db.ForeignKey('user.id')) user = db.relationship('User', backref=db.backref('posts', lazy=True)) The advantage of making relationships is the ability to directly get rows of related table effortlessly i.e. print(post.user.username)
  • 6. Flask-restx Flask restx is a fork of flask-restplus, it was made because the original library isn’t actively maintained. Flask-restx provides built-in support for Swagger 2.0, which will automatically provide documentation for endpoints and models. You can also test the api’s using a doc URL, without the need for Postman. Flask-restx comes with decorators that allow programmers to handle what input’s will be allowed of what types, without writing any logic. The responses are also controlled, extra fields can be automatically removed. Moreover, if you return objects, they’re automatically jsonified.
  • 7. Example setup from flask import Flask from flask_restx import Api app = Flask(__name__) api = Api(app) @api.route('/hello') class HelloWorld(Resource): def get(self): return {'hello': 'world'} Notice that the function is named “get” which corresponds to the request type.
  • 8. Expect & Marshal With model = api.model('Model’, { 'task': fields.String, 'uri': fields.Url('todo_ep’) }) model2 = api.model('Model’, { 'name': fields.String(required=True), }, strict=True) class Todo(Resource): @api.expect(model2) @api.marshal_with(model, skip_none=True) def post(self, **kwargs): return TodoDao(todo_id='my_todo', task='Remember’) @api.expect controls the input, strict means no extra fields are allowed, and required means that the api will fail without the input. You can also do regex pattern matching in the model @api.marshal_with controls the output, Notice that the an object is being returned
  • 9. Sample Project Structure - api - user - __init__.py - schema.py - endpoint.py - model - user.py