Building RESTful APIs with Flask in PyCharm

Quickly make your API accessible in just a few lines of code.

Building APIs can be easier than you think. Say you’ve developed a product or service and would like to provide developer access via a RESTful API quickly, with minimal effort and overhead. The lightweight Flask Python Web framework lets you easily build extendible APIs fast, without the bloat and ceremony of similar tools. Add to this the comprehensive workflow of a modern integrated development environment like PyCharm and you’ll be up and running posthaste.

We’ll start with installing a few prerequisites and set up our working environment so that testing, debugging, and extending the API can happen without too much hopping around. Afterward, we’ll move on to connecting to our database with SQLAlchemy, a Python SQL toolkit and object-relational mapper. We’ll finish up by creating the RESTful API with Flask-Restless, a Flask extension that provides the simple generation of RESTful JSON APIs for database models defined by SQLAlchemy.

Prerequisites

Python – https://www.python.org/download/

PyCharm – http://www.jetbrains.com/pycharm/download/

If you prefer to cheat and skip to the end, the code is available here.

1. Use virtualenv for Managing Packages

Virtualenv helps you manage and maintain your Python environment. Since we’re going to be using a few packages to help build our API, let’s start by creating a virtualenv to keep everything clean and bundled together.

To create a virtualenv in PyCharm:

  1. Open Preferences
  2. Project Interpreter -> Python Interpreters
  3. Click the “Create Virtual Environment” icon

Create Virtual Environment

You can create the virtualenv anywhere, but I personally prefer to create it in a directory inside of my project. For example, if my project name is “my_project”, I would have a folder named “venv” inside of “my_project”.

2. Installing packages

Once your virtualenv is ready, click the “Install” button to begin installing packages. We’ll be installing three packages for our project:

  1. Flask
  2. Flask-Restless (for building the RESTful API)
  3. Flask-SQLAlchemy (for connecting to our database)

Install Package

Simply search and click “Install Package” for each of those three packages.

3. Running Flask’s “Hello World”

Create a new Python file called “app.py” and copy/paste the “Hello world” code from Flask’s homepage: http://flask.pocoo.org/

from flask import Flask
app = Flask(__name__)

@app.route("/")
def hello():
    return "Hello World!"

if __name__ == "__main__":
    app.run()

Because we already have Flask installed as a package in our virtualenv, we can simply right-click on the file and select “Run ‘app'” or “Debug ‘app'”.

Debug 'app'

Then open http://127.0.0.1:5000/ and you should see “Hello world” printed in your browser.

Hello World!

4. Connecting to your database

We’ll use SQLAlchemy to create and connect to our SQLite database.

Replace the previous route code with a few lines of configuration for your database code to make your Python script look like this:

from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy

app = Flask(__name__)

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///people.db'
db = SQLAlchemy(app)

class Person(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    first_name = db.Column(db.Text)
    last_name = db.Column(db.Text)

db.create_all()

if __name__ == "__main__":
    app.run()

View diff

Once you re-run your app, nothing will happen if you try to launch http://127.0.0.1:5000/, but you should notice that your app creates a file called “people.db” in your project directory. “people.db” is your SQLite database.

Double-tap Ctrl on Windows or Cmd on Mac to show the tool windows, then open the Database tools on the top right. We’ll add a new “Data Source” so we can connect to our SQLite database and add some simple data.

Xerial

In the settings, select your “people.db” file in your “Path:”

SQLite - people.db

Click on the “Table Editor” icon to open the Table Editor.

Table Editor

Use the “Add New Row” icon or shortcut to begin adding some data:

Add New Row

5. Creating the RESTful API

We’ll use Flask-Restless to build the RESTful API. You only need to add three lines of code. Import the APIManager, then create the API using the APIManager as shown in the code below:

from flask import Flask
from flask.ext.restless import APIManager
from flask.ext.sqlalchemy import SQLAlchemy

app = Flask(__name__)

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///people.db'
db = SQLAlchemy(app)

class Person(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    first_name = db.Column(db.Text)
    last_name = db.Column(db.Text)

db.create_all()

api_manager = APIManager(app, flask_sqlalchemy_db=db)
api_manager.create_api(Person, methods=['GET', 'POST', 'DELETE', 'PUT'])

if __name__ == "__main__":
    app.run()

Open http://127.0.0.1:5000/api/person to execute a GET request and see the results.*

GET request

You can also select a specific “Person” by id by appending the id to the url like this:
http://127.0.0.1:5000/api/person/1
http://127.0.0.1:5000/api/person/2

Using these APIs, you can now GET, POST, DELETE, and PUT data and you’ve laid the groundwork for your application.

*Unfortunately, at the time of this writing, there is an open bug as of version 0.13 of Flask-Restless. You can either use this fix https://github.com/jfinkels/flask-restless/pull/306/files, revert back to version 12.1, or wait until it gets merged into the 0.14 release. This bug has only been open a couple of days, so hopefully it’s fixed in a timely manner.

Summary

We’ve only scratched the surface of what you can do with PyCharm and Flask. For more details and an in-depth look into building full web applications with PyCharm and Flask, please refer to a webinar we recently conducted at http://blog.jetbrains.com/pycharm/2013/12/video-pycharm-web-magic-building-a-pinterest-clone/

tags: