DEV Community


Posted on • Updated on

Changing Flask-Restplus Base URL

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()
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",
            description='Enrollment API for CRUD operation'
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.

import flask
from application import db
from 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

from application.models import User
from flask import jsonify

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

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

More information:

Top comments (0)