Demo Application
Look at how TheMealDB and TheCocktailDB APIs can be used in an actual application.
We'll cover the following
Let us now look at a Django app that uses TheMealDB API and TheCocktailDB API to provide the user with some delicious recipes.
Live demo
The widget below contains the code for our application. Click the “Run” button to run the app.
""" ASGI config for foodapp_demo project. It exposes the ASGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/4.0/howto/deployment/asgi/ """ import os from django.core.asgi import get_asgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'foodapp_demo.settings') application = get_asgi_application()
-
The
get_cocktails_list()
function, defined in lines 8—17, is used to get the list of the cocktails available in the category selected by the user.- We retrieve the selected category in line 9 and save it in the variable
category
. - We call the API using the
category
variable as the value of the query parameterc
and save the response in theresponse
variable in line 11. - We convert the
response
variable to JSON and send it to be used at the frontend in lines 12—17.
- We retrieve the selected category in line 9 and save it in the variable
-
We use the
get_meals_list()
function, defined in lines 20—29, to get the list of the meals available in the category selected by the user.- We retrieve the selected category in line 21 and save it in the variable
category
. - We use the
category
variable as the value of the query parameterc
. We call the API and save the response in theresponse
variable in line 23. - Then, we convert the
response
variable to JSON and send it to be used at the frontend in lines 24—29.
- We retrieve the selected category in line 21 and save it in the variable
-
We use the
index()
function, defined in lines 32—54, to render the page. It is also used to retrieve the information of the selected meal and the selected cocktail.- The code in line 33 checks if the
POST
request has been generated by the user or not. - In case the
POST
request has not been generated:- We declare an empty variable
context
in line 53.
- We declare an empty variable
- In case a
POST
request has been generated:- We retrieve the selected meal and selected cocktail in line 35 and line 36 respectively.
- We finalize the URLs in lines 39—40.
- We call the APIs using these URLs, in lines 42—43.
- We save the response of TheMealDB API in
response1
in line 42 and the response of TheCocktailDB API is saved inresponse2
in line 43. - We convert the retrieved information to JSON and save it to the
context
variable in lines 44—51.
- The
context
variable is then sent as a response totemplates/foodapp/index.html
in line 54.
- The code in line 33 checks if the