
RESTful API Server Example
This project showcases my vision on how the RESTful API server should be
implemented.
Author's vision update!
I used to use RESTful style APIs for quite a number of projects and this
example was the finest foundation I ended up with, but I always felt
limited by HTTP request-response nature and RESTful resources. Thus, I was
looking for a new solution to the API problem space. I am currently happy
with WAMP-proto specification
(here is my barebones demo), so I can
recommend it. I have also switched to Rust programming language. I am
currently working on async/await-powered implementation of WAMP-proto in
Rust. Stay tuned!
The goals that were achived in this example:
- RESTful API server should be self-documented using OpenAPI (fka Swagger)
specifications, so interactive documentation UI is in place;
- Authentication is handled with OAuth2 and using Resource Owner Password
Credentials Grant (Password Flow) for first-party clients makes it usable
not only for third-party "external" apps;
- Permissions are handled (and automaticaly documented);
- PATCH method can be handled accordingly to
RFC 6902;
- Extensive testing with good code coverage.
I had to patch Flask-RESTplus (see flask_restplus_patched folder), so it can
handle Marshmallow schemas and Webargs arguments.
Here is how it looks at this point of time (live demo):

Single File Example
This example should give you a basic understanding of what you can get with
Flask, SQLAlchemy, Marshmallow, Flask-RESTplus (+ my patched extension), and
OpenAPI.
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_restplus_patched import Api, Namespace, Resource, ModelSchema
# Extensions initialization
# =========================
app = Flask(__name__)
db = SQLAlchemy(app)
api = Api(app)
# Database table definition (SQLAlchemy)
# ======================================
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(), nullable=False)
# Serialization/Deserialization schema definition
# ===============================================
class UserSchema(ModelSchema):
class Meta:
model = User
# "Users" resource RESTful API definitions
# ========================================
users_api = Namespace('users')
api.add_namespace(users_api)
@users_api.route('/')
class UsersList(Resource):
@users_api.response(UserSchema(many=True))
def get(self):
return User.query.all()
@users_api.route('/<int:user_id>')
@users_api.resolve_object('user', lambda kwargs: User.query.get_or_404(kwargs.pop('user_id')))
class UserByID(Resource):
@users_api.response(UserSchema())
def get(self, user):
return user
# Run the RESTful API server
# ==========================
if __name__ == '__main__':
db.create_all()
with db.session.begin(nested=True):
db.session.add(User(name='user1'))
db.session.add(User(name='user2'))
app.run()
Save it, install the dependencies, and run it:
$ pip install -r app/requirements.txt
$ python server.py
Open http://127.0.0.1:5000 and examine the interactive documentation for your
new RESTful API server! You can use any HTTP tools (e.g. cURL, wget,
Python requests, or just a web browser) to communicate with it, or generate
specialized API client libraries for many programming languages using
Swagger Codegen (learn more
in the API Integration section).
Note, this whole repo features much more than that; it demonstrates how I would
organize a production-ready RESTful API server project, so stay tunned.
Project Structure
Root folder
Folders:
app - This RESTful API Server example implementation is here.
flask_restplus_patched - There are some patches for Flask-RESTPlus (read
more in Patched Dependencies section).
migrations - Database migrations are stored here (see invoke --list to
learn available commands, and learn more about PyInvoke usage below).
tasks - PyInvoke commands are implemented here.
tests - These are pytest tests for this RESTful API
Server example implementation.
docs - It contains just images for the README, so you can safely ignore it.
deploy - It contains some application stack examples.
Files:
README.md
config.py - This is a config file of this RESTful API Server example.
conftest.py - A top-most pytest config file (it is empty, but it helps to
have a proper PYTHON PATH).
.coveragerc - Coverage.py (code
coverage) config for code coverage reports.
.travis.yml - Travis CI (automated continuous
integration) config for automated testing.
.pylintrc - Pylint config for code quality
checking.
Dockerfile - Docker config file which is used to build a Docker image
running this RESTful API Server example.
.dockerignore - Lists files and file masks of the files which should be
ignored while Docker build process.
.gitignore - Lists files and file masks of the files which should not be
added to git repository.
LICENSE - MIT License, i.e. you are free to do whatever is needed with the
given code with no limits.
Application Structure
app/
├── requirements.txt
├── __init__.py
├── extensions
│ └── __init__.py
└── modules
├── __init__.py
├── api
│ └── __init__.py
├── auth
│ ├── __init__.py
│ ├── models.py
│ ├── parameters.py
│ └── views.py
├── users
│ ├── __init__.py
│ ├── models.py
│ ├── parameters.py
│ ├── permissions.py
│ ├── resources.py
│ └── schemas.py
└── teams
├── __init__.py
├── models.py
├── parameters.py
├── resources.py
└── schemas.py
app/requirements.txt - The list of Python (PyPi) requirements.
app/__init__.py - The entrypoint to this RESTful API Server example
application (Flask application is created here).
app/extensions - All extensions (e.g. SQLAlchemy, OAuth2) are initialized
here and can be used in the application by importing as, for example,
from app.extensions import db.
app/modules - All endpoints are expected to be implemented here in logicaly
separated modules. It is up to you how to draw the line to separate concerns
(e.g. you can implement a monolith blog module, or split it into
topics+comments modules).
Module Structure
Once you added a module name into config.ENABLED_MODULES, it is required to
have your_module.init_app(app, **kwargs) function. Everything else is
completely optional. Thus, here is the required minimum:
your_module/
└── __init__.py
, where __init__.py will look like this:
def init_app(app, **kwargs):
pass
In this example, however, init_app imports resources and registeres api
(an instance of (patched) flask_restplus.Namespace). Learn more about the
"big picture" in the next section.
Where to start reading the code?
The easiest way to start the application is by using PyInvoke command app.run
implemented in tasks/app/run.py:
$ invoke app.run
The command creates an application by running
app/__init__.py:create_app() function, which in its turn:
- loads an application config;
- initializes extensions:
app/extensions/__init__.py:init_app();
- initializes modules:
app/modules/__init__.py:init_app().
Modules initialization calls init_app() in every enabled module
(listed in config.ENABLED_MODULES).
Let's take teams module as an example to look further.
app/modules/teams/__init__.py:init_app()
imports and registers api instance of (patched) flask_restplus.Namespace
from .resources. Flask-RESTPlus Namespace is designed to provide similar
functionality as Flask Blueprint.
api.route() is used to bind a
resource (classes inherited from flask_restplus.Resource) to a specific
route.
Lastly, every Resource should have methods which are lowercased HTTP method
names (i.e. .get(), .post(), etc). This is where users' requests end up.
Dependencies
Project Dependencies
Build Dependencies
I use pyinvoke with custom tasks to maintain easy and
nice command-line interface. Thus, it is required to have invoke Python
package installed, and optionally you may want to install colorlog, so your
life become colorful.
Patched Dependencies
- flask-restplus is patched to handle marshmallow schemas and webargs
input parameters
(GH #9).
- swagger-ui (the bundle is automatically downloaded on the first run