Search code examples
pythonjsonflaskpostmanapi-design

Trying to POST from Postman - getting 405 error in Flask REST API


Trying to use Postman to test and see if my post method of an API I'm building works. I keep getting a 405 error, suggesting to me that the functionality of posting isn't even available. But it's a pretty straightforward class, so I can't see what's wrong.

from flask.views import MethodView
from flask import jsonify, request, abort

class BookAPI(MethodView):

    books = [
        {"id":1, "title":"Moby Dick"},
        {"id":2, "title":"Grapes of Wrath"},
        {"id":3, "title":"Pride and Prejudice"}
    ]

    def get(self):
        return jsonify({"books": self.books})

    def post(self):
        if not request.json or not 'title' in request.json:
            abort(400)

        book = {
        "id": len(self.books) + 1,
        "title": request.json['title']
        }

        self.books.append(book)
        return jsonify({'book':book}), 201

The get method is working fine. I can see it on my localhost. But when I try to post to my localhost with postman - 405 error

This is all I'm posting to http://localhost/books/

{
   "title": "Frankenstein"
}

Solution

  • Thanks for the additional details, I tried running your application and it does work for me, the only change I made is the actual URL. You have registered your books api under the /books prefix. This is the specific place in your code https://github.com/branhoff/wishlist-api/blob/ee9fc696069d98513a89c249d23874d429684d54/book/views.py#L7

    curl -X POST -H "Content-Type: application/json" -d '{"title": "GoT"}' http://localhost:80/books/
    

    enter image description here