Get Example
In this section, we will override the get
function to fetch either product or product type information from the database.
This determination will be made based on a flag provided as a query parameter in the request. This will showcase the
self.request_parameters
attribute introduced in the previous section, which allows for easy retrieval of query and body parameters.
Let’s begin by importing the relevant database objects:
from q2_sdk.hq.db.product import Product
from q2_sdk.hq.db.product_type import ProductType
We will also need to import the to_bool
function, which can be used to convert strings to booleans.
This will come in handy when retrieving the flag from our request:
from q2_sdk.tools.utils import to_bool
Now that we have all of the necessary imports, we can override the get() method:
async def get(self, *args, **kwargs):
self.set_header("Content-Type", "application/json")
object_class = Product(self.logger, hq_credentials=self.hq_credentials)
product_types = to_bool(self.request_parameters.get("getProductTypes"))
if product_types:
object_class = ProductType(self.logger, hq_credentials=self.hq_credentials)
data = await object_class.get()
product_data = []
for row in data:
product_data.append({x.tag: x.text for x in row.getchildren()})
response = self.return_data(product_data)
self.logger.info(response)
self.write(response)
First we set our headers, which will always be applications/json
for all requests to the API.
We instantiate the Product or ProductType database objects based on the getProductTypes
flag retrieved
from self.request_parameters
. The to_bool() function can be utilized to convert the string provided
in the request to a python recognizable boolean. Each object has a get() method that can then be invoked to
retrieve the corresponding information.
Next, we populate a product_data list with the information
returned from each xml row in the response. The product_data list can then be passed in to the self.return_data
function,
which will format the response in a way that the API can consume. Finally, we send our response using the self.write() method.