Home > Enterprise >  How to get an ID parameter from the URL with flask and Pymongo
How to get an ID parameter from the URL with flask and Pymongo

Time:07-25

Sorry I'm new to using python.

I am trying to query a mongo database using a string ID I have generated for each document(book). I am more familiar with Express and Javascript where I could easily use the req.params object to retrieve an id from a URL. So if I wanted to get a specific book I could easily run http://localhost:5000/books/abc and it would return the book where the id = abc

However I cannot find the equivalent or similar with flask. The closest thing I have found is the request.args.get() which means in order to get a book I have to write the URL like so http://localhost:5000/books/id?id=abc

Here is my current code below

def get_book(data):
    books = db.books
    result = books.find_one({'_id': data})
    return jsonify(result)
@book.route('/id', methods=['GET'])
def find_one_book():
    id = request.args.get('id')
    response = get_book(id)
    return response

This works fine but I would prefer to be able to go to http://localhost:5000/books/abc in order to get a book rather than having to explicitly say the id inside my url string like so http://localhost:5000/books/id?id=abc.

Thanks all!

CodePudding user response:

You can use a variable rule like so:

@app.route('/user/<username>')
def show_user_profile(username):

See the documentation here: https://flask.palletsprojects.com/en/2.1.x/quickstart/#routing

CodePudding user response:

@app.route("/books/<id>", methods=['GET'])
def find_one_book(id):
  response = get_book(id)
  return response
  • Related