Search code examples
pythonapihttpflask-restfulhttp-status-code-405

HTTP Status 405 and Restful API in Flask Python


The general goal

For a webshop without frameworks I am working on, I need to define a good route to the restful API of the application.

The problem

When I load the page (for example: localhost:.../api/favorites) I get the HTTP 405 error with the message: "Method not allowed".

I have searched for different kinds of sources such as a forum post about the HTTP 405 error: HTTP Status 405 - Method Not Allowed Error for Rest API. But I could not discover how this would solve my error.

And I have studied the 'Flask Documentation' and have found an example:

@app . url_defaults 
  def add_language_code ( endpoint , values ) : 
    if lang_code in values or not g . lang_code : 
      return 
    if app . url_map . is_endpoint_expecting ( endpoint , lang_code ) : 
      values [    lang_code ] = g . lang_code

But I could not find what I am doing exactly wrong or is missing, and most important: why do I get that HTTP 405 error with this @api route.

Explanation of my project:

In the database I have a table named 'favorites' with the columns 'user_id' and 'product_id. On the /favorites page I want to load data from the favorites table to show the favorited items by a (specific) user. But first of all I want just to import the data from the database. I want to do this by retrieving the product_id from the database (first route). And later on I want to specify that it is only possible to favorite items when you have ordered it. (orderhistory or combined by user_id) (second route).

The front-end of the webshop is made with html/css/javascript and the back-end is flask by python.

The question:

Is the error of the HTTP 405 message due to a fault in this piece of code that routes to the API?

Could someone understand and maybe explain my precise code mistake so I can try to fix it by knowing what is causing the error?

First route

@api.route('/favorites/<int:product_id>', methods = ['GET'])
   def get_favorites(product_id):
      return favorites.get_favorites(product_id)

Second route

@api.route('/favorites/<int:user_id>')
   def get_favorites_by_user_id(user_id):
     return favorites.get_favorites_by_user_id(user_id)

Thank you very much in advance!


Solution

  • It would be nice if you can show your front end code. But I think you made a post request to the backend without listing methods=['GET', 'POST'] in your logic. Thus getting a 405.

    Just add the POST to your list