background preloader

Designing a RESTful API with Python and Flask

Designing a RESTful API with Python and Flask
In recent years REST (REpresentational State Transfer) has emerged as the standard architectural design for web services and web APIs. In this article I'm going to show you how easy it is to create a RESTful web service using Python and the Flask microframework. What is REST? The characteristics of a REST system are defined by six design rules: Client-Server: There should be a separation between the server that offers a service, and the client that consumes it.Stateless: Each request from a client must contain all the information required by the server to carry out the request. What is a RESTful web service? The REST architecture was originally designed to fit the HTTP protocol that the world wide web uses. Central to the concept of RESTful web services is the notion of resources. The HTTP request methods are typically designed to affect a given resource in standard ways: The REST design does not require a specific format for the data provided with the requests. Designing a simple web service

Designing a RESTful API using Flask-RESTful This is the third article in which I explore different aspects of writing RESTful APIs using the Flask microframework. The example RESTful server I wrote before used only Flask as a dependency. Today I will show you how to write the same server using Flask-RESTful, a Flask extension that simplifies the creation of APIs. The RESTful server As a reminder, here is the definition of the ToDo List web service that has been serving as an example in my RESTful articles: The only resource exposed by this service is a "task", which has the following data fields: uri: unique URI for the task. Routing In my first RESTful server example (source code here) I have used regular Flask view functions to define all the routes. Flask-RESTful provides a Resource base class that can define the routing for one or more HTTP methods for a given URL. The add_resource function registers the routes with the framework using the given endpoint. Request Parsing and Validation Generating Responses I can do this: Conclusion

How To Structure Large Flask Applications Introduction There are many methods and conventions for structuring Python web applications. Although certain frameworks are shipped with tools (for scaffolding) to automate -- and ease -- the task (and the headaches), almost all solutions rely on packaging / modularizing applications as the codebase gets distributed [logically] across related files and folders. The minimalist web application development framework Flask, has its own - blueprints. In this DigitalOcean article, we are going to see how to create an application directory, and structure it to work with re-usable components created with Flask's blueprints. Glossary 1. 2. 3. Prepare The Operating SystemSetting up Python, pip and virtualenv 4. Creating Application FolderCreating A Virtual EnvironmentCreating Application FilesInstalling Flask 5. Module BasicsModule Templates 6. Edit run.py using nanoEdit config.py using nano 7. Flask: The Minimalist Application Development Framework Our Choices In This Article Flask-SQLAlchemy Flask-WTF

Authomatic So you want your app to be able to log a user in with Facebook, Twitter, OpenID or whatever? First install Authomatic through PyPi, or clone it from GitHub. $ git clone Now it’s dead simple (hence the Deadsimpleauth). Make an instance of the Authomatic class.Log the user in by calling the Authomatic.login() method inside a request handler. Note The interface of the library has recently been changed from: import authomaticauthomatic.setup(CONFIG, 'secret') to more flexible: from authomatic import Authomaticauthomatic = Authomatic(CONFIG, 'secret') The old interface will be availabe up to version 0.1.0, but you will recieve deprecation warnings in the log. If everything goes good, you will get a User object with information like User.name, User.id or User.email. Instantiate Authomatic You need to pass a Config dictionary and a random secret string used for session signing and CSRF token generation to the constructor of the Authomatic class. Log the User In

Saturday morning hack: a little note-taking app with Flask A couple Saturdays ago I spent the morning hacking together a note-taking app. I'm really pleased with the result, so I thought I'd share the code in case anyone else might find it useful. The note-taking project idea came about out of necessity -- I wanted something that worked well from my phone. While I have a personal wiki site I've used for things like software installation notes or salsa recipes, I've also noticed that because it's so cumbersome to use from my phone, I often end up emailing things to myself. Here is how the app appears on a narrow screen like my phone: And here it is on my laptop: Because markdown is a bit difficult to use when you're not in a nice text editor like vim, I've added some simple toolbar buttons to the editor: If you'd just like to see the code, here is the multi-file gist. Feature review Based on the problems I outlined, the notes app needed to have to following features: The tools On the frontend, the first choice I made was to use Bootstrap. Python code

SyrusAkbary/Flask-SuperAdmin Structuring flask apps, a how-to for those coming from Django The other day a friend of mine was trying out flask-peewee and he had some questions about the best way to structure his app to avoid triggering circular imports. For someone new to flask, this can be a bit of a puzzler, especially if you're coming from django which automatically imports your modules. In this post I'll walk through how I like to structure my flask apps to avoid circular imports. I'll walk through the modules I commonly use in my apps, then show how to tie them all together and provide a single entrypoint into your app. Project layout I use a structure that may look familiar to users of the django framework: In a little bit I'll get to the reason "main.py" is the secret sauce, for now though I'll focus on the other bits. app.pymodels.pyauth.pyadmin.py / api.pyviews.pymain.py app.py Every flask application needs an "app.py", whether you call it that or not. """I keep app.py very thin.""" That's it! models.py auth.py admin.py / api.py Here is admin.py: And here is api.py: views.py

Flask-Security — Flask-Security 1.5.2 documentation Flask-Security allows you to quickly add common security mechanisms to your Flask application. They include: Session based authenticationRole managementPassword encryptionBasic HTTP authenticationToken based authenticationToken based account activation (optional)Token based password recovery / resetting (optional)User registration (optional)Login tracking (optional)JSON/Ajax Support Many of these features are made possible by integrating various Flask extensions and libraries. Additionally, it assumes you’ll be using a common library for your database connections and model definitions.

Large app how to · mitsuhiko/flask Wiki This document is an attempt to describe the first step of a large project structure with flask and some basic modules: SQLAlchemyWTForms Please feel free to fix and add your own tips. Installation Flask Flask Installation I recommend using virtualenv: it is easy and allows multiple environments on the same machine and doesn't even require you to have super user rights on the machine (as the libs are locally installed). Flask-SQLAlchemy SQLAlchemy provides an easy and advanced way to serialize your object to different types of relational databases. pip install flask-sqlalchemy More here about the Flask-SQLAlchemy package Flask-WTF WTForms provides an easy way to handle user's data submission. pip install Flask-WTF More here about the Flask-WTF package Overview Ok, so from now, we should have all the libs ready. /config.py /run.py /shell.py /app.db /app/__init__.py /app/constants.py /app/static/ For every module (or sub app... ) we'll have this file structure (here for the users module) Config #! Testing

swaroopch/flask-boilerplate Getting bigger with Flask | Tech & statup blog by maximebf My last post about creating websites with Flask covered the steps to create a simple application. What happens when it grows bigger? In this post I will take as example a common use case for a web app: a public section (homepage, tour, signup, login) a member only section (the app, user settings) an api Each member will have its own subdomain (ie: if my username is maximebf, I get the maximebf.example.com subdomain). I’ll assume the same file organization as I described in my previous post. Getting modular with Blueprints Flask provides a feature called Blueprints which let your organize your app as modules. I like to create a modules folder in my application directory where all my module files will be stored. example/ modules/ __init__.py public.py member.py api.py To create a module, you initializes a Blueprint object which acts in the same way as the Flask object. Each blueprint can have its own templates folder. I use the same logic for static files. Wildcard subdomains

Flask-Exceptional — Flask-Exceptional 0.5.2 documentation Flask-Exceptional adds Exceptional support to Flask. Exceptional tracks errors in your application, reports them real-time, and gathers the info you need to fix them fast. Visit to give it a try. Installation The remaining documentation assumes you have access to an Exceptional account. $ pip install Flask-Exceptional or alternatively with easy_install: $ easy_install Flask-Exceptional Quickstart After installing Flask-Exceptional, all you have to do is create a Flask application, configure the Exceptional API key, and create the Exceptional object. from flask import Flaskfrom flask.ext.exceptional import Exceptional app = Flask(__name__)app.config["EXCEPTIONAL_API_KEY"] = "exceptional_forty_character_unique_key"exceptional = Exceptional(app) Your application is configured for cloud-based error monitoring! Exceptional.test(app.config) Check out the following section for more detail on the available Flask-Exceptional configuration settings. Configuration Note Changelog

Related: