1

I have an existing mysql database, and I'm trying to create an API to access it, but I'm receiving a 404 error. I have two versions of code that don't work.

Could someone please point me in the right direction?

URL I'm using: http://127.0.0.1:5000/api/email

v1:

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

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://pathtodb/emails'
db = SQLAlchemy(app)

class Email(db.Model):
    __tablename__ = 'emails'
    id = db.Column(db.Integer, primary_key=True)
    status = db.Column(db.String(20))
    email = db.Column(db.String())

    def __init__(self, status, email):
        self.status = status
        self.email = email

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

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

v2:

from flask import Flask
from flask.ext.restless import APIManager
from sqlalchemy import *
from sqlalchemy.ext.declarative import declarative_base

app = Flask(__name__)
Base = declarative_base()
engine = create_engine('mysql+pymysql://pathtodb/emails', echo=True)
metadata = MetaData(bind=engine)

class Email(Base):
    __tablename__ = Table('emails', metadata, autoload=True)
    id = Column(Integer, primary_key=True)
    status = Column(String(20))
    email = Column(String())


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

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

URL I'm using: http://127.0.0.1:5000/api/email

SO03112
  • 178
  • 2
  • 12

1 Answers1

4

With flask-restless the links are generated automatically when the method api_manager.create_api() is called, with this format :

'http://127.0.0.1:5000/api/{tablename}'  # default domain and port

where {tablename} is the __tablename__ given to the model class, not the class name called in the method.

The doc mentioned an example here.

PRMoureu
  • 12,817
  • 6
  • 38
  • 48
  • 1
    btw, not sure about the version you are using, but the import could be `from flask_restless import APIManager` to avoid a deprecated warning – PRMoureu Oct 31 '17 at 20:03