Implement GET Endpoint for Listing Products
Implement the products API using flask for listing all the products.
Read (aka retrieve) is one of the fundamental operations while dealing with data. In the realm of the web and internet in general, the GET method is associated with the retrieval of data. Since REST uses HTTP to perform data-related operations, the GET method is used to retrieve data in any of its supported representations. There are two ways the GET method can be used in a REST API:
- Retrieve a collection of resources
- Retrieve a specific resource from a collection
In this lesson, we’ll look at how to provide an API that returns a collection of products. As we’ve selected the Flask framework, let’s see how to set up a project based on Flask and implement GET functionality.
Steps
Create a directory named
server
. Within the directory, add a__init__.py
file.Create a Python package named
api
within the directory.Add a new file named
data_store.py
in theapi
package. Opendata_store.py
and add the following code.
products = [{"id": "1","name": "servlet-container","description": "container for servlet","version": "3.0"},{"id": "2","name": "ejb-container","description": "container for ejb","version": "3.0"}]
Add another file named
products_api.py
and open it.Add the following imports.
from flask import (request, jsonify, Blueprint)from .data_store import products
Create a
Blueprint
namedproducts_api
with the URL prefix‘/api/’
. Assign it toproducts_blueprint
...