Get a Random Cocktail
Learn how we can get a random cocktail recipe using this API.
We'll cover the following
There are times when we want to drink something but are not sure what we should go for. TheCocktailDB API can help us in this kind of situation.
Fetch for a random cocktail
TheCocktailDB API provides us with an endpoint that we can use to get the recipe for a random cocktail. The base URL of this endpoint is https://www.thecocktaildb.com/api/json/v1/1/random.php
Request parameter
This endpoint doesn’t have any request parameter.
We simply call the base URL to get a random cocktail. The code below shows how we can call this endpoint.
const endpointUrl = new URL('https://www.thecocktaildb.com/api/json/v1/1/random.php');const options = {method: 'GET'};async function fetchRandomDrink() {try {const response = await fetch(endpointUrl, options);printResponse(response);}catch (error) {printError(error);}}fetchRandomDrink();
Following is a brief explanation of the above code:
Line 1: We define the URL of the endpoint.
Lines 3–5: We set the appropriate request type.
Lines 7–16: We define the
fetchRandomDrink()
function that calls the endpoint and prints the response.Line 18: We call the
fetchRandomDrink()
function.
We've altered the printResponse()
function in the code widget below. It'll now use the information returned by the API to provide us with the recipe for the random drink along with its image. Click the "Run" button to see the recipe. Each time the code is executed, it fetches a new cocktail recipe.
const endpointUrl = new URL('https://www.thecocktaildb.com/api/json/v1/1/random.php');const options = {method: 'GET'};async function fetchRandomDrink() {try {const response = await fetch(endpointUrl, options);printResponse(response);}catch (error) {printError(error);}}fetchRandomDrink();
Response fields
The table below contains some important response fields:
Response field | Type | Description |
| Integer | The API-assigned ID of the drink |
| String | The name of the drink retrieved by this endpoint |
| String | The category of the drink |
| String | The instructions to prepare the drink |
| String | A link for the image of the drink |
| String | The names of the required ingredients to make the drink |
| String | The quantity of ingredients required to make the drink |
Note: The value of some of the response objects might be
null
depending on the availability of the data.