A Complete Code Tutorial To Working With APIs In Flask

In this post, I want to show you how to quickly put together a complete REST API using Flask. As you might know, Flask is a perfect fit for the job! Our example creates a movies API but you can follow this for any API you want to create! Here's what we'll cover: An API needs a data source, a URL scheme, and request methods that clients use to access resources. To keep things simple and focused on the API, we skip setting up a database and use an in-memory array to hold our movies. This allows us to focus on the API request methods. We set up our API code in a new Python file called app.py . We import these Flask helpers : Our first API route handles listing all movies. Here is the code that does this. We use a @app.route decorator to set the request URL. Our response returns a JSON formatted collection with the movies from our data store. When using a database like MySQL or MongoDB, this is where you would integrate database calls to fetch movie data. Here is how you implement retrieving a single movie. In this method, we match the movie based on the id in the URL. If one is found, we send it back, using jsonify to format it as JSON. When creating a new movie, a REST client sends the new movie's attributes in a JSON payload. It might look as shown in the image. Here is the method in our app that takes this payload and creates new movies. In this method, we first check if the user supplied a title for the new movie . If not, we abort the request. Note the 400 error code. Otherwise, we create a new movie with the supplied title , plot , and other attributes. We save it in the movies data store and return a JSON result with the saved movie . Our method here is also the most complex in this example. That's because it has to handle multiple moving parts. Let's break it down. We match the movie to update based on the id in the URL. If no match is found, we abort the request. We do the same if the user has not supplied a title or plot , or if the user has not supplied any valid JSON . Otherwise, we update the movie with the attributes supplied in request.json . If an attribute is not supplied in the request , we recycle its old value and use that. We then save the updated movie in our data store. The API is almost complete! Here's the code that handles delete requests. We match the movie based on the id in the URL. If a match is not found, we abort the request. Else, we remove the movie from our data store. We then return a JSON with the result . That completes our movies API! For more on Flask, check out our course Fullstack Flask where we've focused on building a whole, master-level SaaS app end to end.

Thumbnail Image of Tutorial A Complete Code Tutorial To Working With APIs In Flask