• Post category:Python
  • Reading time:3 mins read

ABOUT API:-

In order to communicate two software, we need an interface from which data can be transferred from one platform to another. For example, if today’s port 80 does not exist then may be we won’t be able to use the internet. Likewise, the API gives us above mentioned type of functionality.

WHAT ARE THE TYPES OF API ?

There are two types of APIs:

A. SOAP API:

In this API, the data is represented in XML format. It gives us the functionality to validate data. If you want to know more about the SOAP API please visit; https://www.altexsoft.com/blog/engineering/what-is-soap-formats-protocols-message-structure-and-how-soap-is-different-from-rest/

B. REST API:

In this, the API data is represented in the JSON format. So now, in this blog we will discuss how to get data using REST API. I am using requests which is a python HTTP library.

Let’s walk through!

  1. Install requests using pip

→check wether requests are installed or not using pip freeze

→if not installed use pip install requests command

2. Basic function which will be used

→ response = requests.get( url = ”http://” )

            to send get request on any url

→ json_result = response.json()

            to convert json data in python dictionary

So over here, we are creating a program to show the names of cocktail and the names starting from a reference site;

https://www.thecocktaildb.com/api.php?ref=apilist.fun (thanks for giving an API for public)

The above site is giving API to search all cocktail name starting from a character.

https://www.thecocktaildb.com/api/json/v1/1/search.php?f=<first char>  it is returning a lot of data but we are only printing name.

Let the first char be m

then the URL will be https://www.thecocktaildb.com/api/json/v1/1/search.php?f=m

Now, let’s write the program!

import requests
def print_cocktail_name(name_char):
name_char = str(name_char)
api_url = /https://www.thecocktaildb.com/api/json/v1/1/search.php?f=/ + name_char
try:

response = requests.get( url = api_url )
except:
print('sorry internet connection is not available')
return 0
if response.status_code==200 :
try:
json_result = response.json()
for cocktail_details in json_result['drinks']:
print(cocktail_details['strDrink'])
except:
print('result in invalid format')
else:
print('server down')
print_cocktail_name('m')

Output:

Share Post on:

Leave a Reply