DEV Community

loading...

Changing Flask-Restplus Base URL

Sekti
Keep moving forward. Learn well not learn fast.
Updated on ・1 min read

Recently, I have an issue when creating API using Flask.

The basic syntax to create an API using Flask-Restplus is:

from flask import Flask
app = Flask(__name__)

from flask_restplus import Api
api = Api()
api.init_app(app)
Enter fullscreen mode Exit fullscreen mode

However, this basic syntax will override the index route on your webpage.
So to fix this, blueprint should be imported.

from flask import Flask, Blueprint
from flask_restplus import Api

app = Flask(__name__)
blueprint = Blueprint('api', __name__, url_prefix='/v1')
api = Api(blueprint,
            title="Enrollment API",
            version='v0.1',
            description='Enrollment API for CRUD operation'
        )
app.register_blueprint(blueprint)
Enter fullscreen mode Exit fullscreen mode

From here the API base url will not overriding the index route anymore.
Now lets add the api to get user data by pulling jsonify and importing the model.

models.py

import flask
from application import db
from werkzeug.security import generate_password_hash, check_password_hash

class User(db.Document):
    user_id     = db.IntField(unique=True)
    first_name  = db.StringField(max_length=50)
    last_name   = db.StringField(max_length=50)
    email       = db.StringField(max_length=30, unique=True)
    password    = db.StringField()

    def set_password(self, password):
        self.password = generate_password_hash(password)

    def get_password(self, password):
        return check_password_hash(self.password, password)

Enter fullscreen mode Exit fullscreen mode

route.py

from application.models import User
from flask import jsonify

@api.route('/api','/api/')
class GetAndPost(Resource):
    ''' Get All '''
    def get(self):
        return jsonify(User.objects.all())
Enter fullscreen mode Exit fullscreen mode

From the code above, now the API can be access via localhost:5000/v1/api. The API will return all User in Jsonformat

PS:
Werkzeug need to downgrade to 0.16.1 to use flask_restplus
pip install Werkzeug==0.16.1

More information:
https://github.com/noirbizarre/flask-restplus/issues/286

Discussion (0)

Forem Open with the Forem app