0

I'm trying to build a simple Flask application with Swagger. So far, after a few tutorials this is what my main.py looks like:

import logging
import os
import random

from flask_restx import Api, Resource, fields

from src import create_app

app = create_app(os.getenv('env'))
api = Api(app, version='1.0', title='Sample API',
          description='A sample API', doc='/api')

ns = api.namespace('userinfo', description='Python Microservice')
user = api.model('user', {
    'name': fields.String(required=True, description='Employee Name'),
    'role': fields.String(required=True, description='Employee Role'),
})

USERS = {'user_1000': dict(name="Elizabeth Lemon", role="Head"), 'user_1001': dict(name="Jack Donaghy", role="CEO"),
         'user_1003': dict(name="Kenneth Parcell", role="Page")}

resource_fields = api.model('Resource', {
    'name': fields.String,
    'role': fields.String
})


@ns.route('/')
@api.doc(responses={200: 'Success', 201: 'Created'})
class UserInfo(Resource):
    """View list of all users, POST to add new user"""

    def get(self):
        """List  all users"""
        return [{'id': u_id, 'user_info': user_info} for u_id, user_info in USERS.items()]

    @api.doc(body=resource_fields)
    def post(self):
        """Create a new user"""
        data = api.payload
        user_id = f"user_{random.randint(1004, 9999)}"
        USERS[user_id] = dict(name=data['name'], role=data['role'])
        logging.info(f"Created user {user_id} for {data['name']}")
        return dict(user_id=user_id), 201


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

The create_app() function is defined in an __init__.py as follows:

def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config_by_name[config_name])
    setup_logging(app)
    return app

Now, when I head over to localhost:5000/api I see the swagger page load correctly with the GET/POST documentation. However, when I hit localhost:5000 I get a URL not found error - understandable since I have not defined a / route yet - which is where I'm stuck!! How do I define a / route in my main.py? From what I understand, all endpoints currently served are /userinfo/(GET, POST) and /api. I want to add that / endpoint to facilitate a simple check of whether the application is started up

I'm new to building microservices with Flask in Python. Integrating swagger actually changed the face of main.py coz earlier w/o swagger, all my routes were annotated with app.route('/') so I could have a / endpoint.

Saturnian
  • 1,686
  • 6
  • 39
  • 65

1 Answers1

0

By default, flask-restx uses namespace name to construct URLs (/<name> prefix), but you can specify a prefix to all URLs explicitly via the path argument. Something like:

ROOT_NS = api.namespace(
    'section-name-that-will-be-displayed-at-swagger--fill-free-to-rename',
    path='/'
)