Home > Back-end >  Flask webserver with React client and RestFull API
Flask webserver with React client and RestFull API

Time:05-26

How are you?

I'm trying to maintain two services on the same flask web server: A React client (available in "/") and a RestFull API (available in "/api/").

However, all routes are directed to the client and I cannot register the Blueprint to "/api".

@app.route('/', defaults={'path': ""})
@app.route('/<path:path>')
def client_route(path):
    return 'Client'


app.register_blueprint(routes, url_prefix="/api")
""" Registro de rotas da aplicação """

printscreen code

I need routes starting with "/api" to call the API routes, while all other routes (*) call Client React.

Can anybody help me??

CodePudding user response:

main_view.py

bp = Blueprint('main', name, url_prefix='/api')

app.py

app.register_blueprint(main_view.bp)

When setting the blue print, enter '/api' instead of 'prefix = /' section. oh You've already set it up like that, but in my case I write above .

I hope this helps.

CodePudding user response:

You must enter api not \api.

Here is a link on how blueprints work: https://realpython.com/flask-blueprint/

CodePudding user response:

I found the solution!

You just need to swap the order of the register, like that:

app.register_blueprint(routes, url_prefix="/api")
""" Registro de rotas da aplicação """


@app.route('/', defaults={'path': ""})
@app.route('/<path:path>')
def client_route(path):
    if path != "" and os.path.exists(app.static_folder   '/'   path):
        return send_from_directory(app.static_folder, path)
    else:
        return send_from_directory(app.static_folder, 'index.html')

(*) And you may use this React code to serve the webapp correctly.

Thaks!!

  • Related