So I'm trying to make an API, using Flask-Restful, but all the examples I find put everything into one app.py file. I found information in the Flask-Restful docs explaining how to structure your API, but it doesn't include anything for using a database. I've posted what I've come up with, and it works if I hard-code some data, but when I import the db
into users.py
I get an error ImportError: cannot import name 'db'
. So, what is the best way to structure an API to bring in your data from a database?
Structure
myapi
run.py
api
__init__.py
resources
__init__.py
user.py
myapi/run.py
from api import app
app.run()
myapi/__init__.py
from flask import Flask
from flask.ext.restful import Api
from flask.ext.sqlalchemy import SQLAlchemy
from api.resources.user import User
app = Flask(__name__)
app.debug = True
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://localhost/myapi'
api = Api(app)
db = SQLAlchemy(app)
api.add_resource(User, '/user')
../resources/user.py
from flask.ext.restful import Resource
from api import db
class User(Resource, db.Model):
def get(self):
return {'class': 'user', 'first': 'john', 'last': 'doe'}