Search code examples
pythonflaskflask-restx

Api endpoints do not register in Flask-Restx


I've been following some tutorials(basic examples), trying to create a RESTful API with Flask-Restx. However, when I try to register endpoints with a more complex project structure(following this example), no API endpoints get registered. I defined the namespace of an endpoint and tried to register that in app.py:

from flask import Flask, Blueprint, url_for, jsonify
from flask_login import LoginManager
import settings
from database import db
from BE.api.__init__ import api
from BE.api.endpoints.images import ns as image_api
from werkzeug.middleware.proxy_fix import ProxyFix



app = Flask(__name__)
app.wsgi_app = ProxyFix(app.wsgi_app)

#flask_restx API supports prior flask_restplus api
def configure_app(app):
    app.config['SWAGGER_UI_DOC_EXPANSION'] = settings.RESTPLUS_SWAGGER_EXPANSION
    app.config['RESTPLUS_VALIDATE'] = settings.RESTPLUS_VAL
    app.config['RESTPLUS_MASK_SWAGGER'] = settings.RESTPLUS_MASK_SWAGGER
    app.config['SQLALCHEMY_DATABASE_URI'] = settings.SQLALCHEMY_DATABASE_URI
    app.config['UPLOAD_FOLDER'] = settings.UPLOAD_FOLDER
    app.config['MAX_UPLOAD_LENGTH'] = 24 * 1024 * 1024  # limits filesize to 24 mb

def init_app(app):
    configure_app(app)
    api.add_namespace(image_api)
    app.register_blueprint(api, url_prefix='/api/1')
    api.init_app(app)
    db.init_app(app)
[....main etc]

The API init.py looks as follows:

from flask_restx import Api


api = Api(version='0.1', title='Backend API', description='Backend API for sticker generation')

and the endpoint I want to register:

from flask import request, flash, Blueprint, redirect, send_file
from flask_restx import Resource, Namespace
from BE.database import db as database
from BE.database.models import Image as dbImage
from BE.api.api_definition import image
[....]

ns = Namespace('image', path='/image', description='Available Ops')

@ns.route('/test')
class TestClass(Resource):
    def get(self):
        return "Hello World"
[....]

While @app.route('/') works in app.py, the @ns.route('/') remains unsuccessful and I'm at a loss as to why.


Solution

  • Answering my own question:

    Turns out that running app.py from PyCharm does not run via main() or was configured in a wrong way, but rather appears to just launch the Flask server from the initial app = Flask(__name__). Therefore configure_app() or init_app() never get called. Transforming the project layout to something more closely resembling Flask's intended layout resolves that in part, resulting in the intended endpoints to work.