Building an API Endpoint in Flask for Returning All Records with a GET Request
In the last guide, we walk through how we could create our very first endpoint that allowed us to create guides programmatically. So now with that in place, I think the most natural endpoint to create next would be to have a world that we can hit to see all of the guides in the system.
Guide Tasks
  • Read Tutorial
  • Watch Guide Video
Video locked
This video is viewable to users with a Bottega Bootcamp license

So it's come down here and add another comment just so it's very clear when you're looking through the source code which was each one of these endpoints does.

app.py

# Endpoint to query all guides

And as you may expect now since we've done this a few times we're going to use a route decorator.

app.py

# Endpoint to query all guides
@app.route("/guides", methods=["GET"])
def get_guides():
    all_guides = Guide.query.all()
    result = guides_schema.dump(all_guides)
    return jsonify(result)

Now notice here how I'm using what we had on line 29. I'm not using the single guide schema, I'm using the multiple, the one where we said that many are true. This gives us the ability to work either with single guides or multiple guides.

OK let's save this and run our server. If we don't have any spelling mistakes or typos then this should work. So let's say python app.py Now if we open up Postman, we are no longer going to be using a POST request. Remember, we're going to use a get request and we're not going to guide, We're going to go to guides.

So now if I type send then this should work and we should get back that guide that we created in the last lesson. And that works.

large

Now that's kind of boring. Let's go back out and a new guide, just to make sure that this is working. One hint that this is working is notice the one change we had is it now is returning a list of guides, as we can see from the square brackets here.

But let's not just trust that so I'm going say POST and go to a localhost:5000/guide inside of the body. Let's say my second guide and we can leave the content they're the same. So now if I hit send on this. That looks like it worked.

large

It has some content and then 'my second guide' notice that it doesn't always keep the order there, but that's fine. And so now if I say localhost:5000/guide and make it a GET request and hit send, Now you can see that our query is working so we know that we save two guides to the database and now those are getting returned.

large

Just like this. So nice job. If you went through that we now have two endpoints completed for our guides API.

Source Code