API Handling in Python

API Handling in Python

Β·

2 min read

Namaste Coders πŸ™

In this article, we will discuss how to retrieve desired data from a given API.

What is API πŸ€”

Application Programming Interface (API) is a day to day tool used throughout programming. One must be aware to handle the APIs as it will be a part of your day to day coding work πŸ‘©β€πŸ’».

Modules used

  • json
  • requests (need to install using pip install requests)

We are going to retrieve data from free APIs available.

Let's check random user API which returns data of a user. We will try to fetch firstname and lastname of the user.

image.png

It looks like python dictionary, but it is JSON Response, from which we need to fetch the data.

https://jsonformatter.org/ can be used to format the response beautifully πŸ’ƒ.

image.png

import json
import requests

random_user_api="https://randomuser.me/api"



def random_user(api):
    try:
        res= requests.get(api)
        #print(type(res)) #<class 'requests.models.Response'>
        #print(res) #<Response [200]>

        res_text = json.loads(res.text)
        #print(type(res_text))#<class 'dict'>


        fname=res_text['results'][0]['name']['first']
        lname=res_text['results'][0]['name']['last']
        print(f"firstname is : {fname}")
        print(f"lastname is : {lname}")

    except BaseException as err:
        print(err)


if __name__ == "__main__":
    random_user(random_user_api)

requests module is used to make a http get request that will return response code 200, in case of a success.

json module helps in converting json response into Python object (dict) using json.loads() method.

While working with APIs we need to dive deep enough to fetch the desired data, by keeping the python data structures in mind. Sometimes, we need to apply the key value as it is dictionary and sometimes we might need to use index number if list is the data structure.

Let's dig deep one by one

        print(res_text["results"])
        print("#######33")
        print(res_text["results"][0])
        print(res_text["results"][0]['name'])
        print(res_text["results"][0]['name']['first'])

image.png

The End

Do create the project and tag meπŸ‘©β€πŸ«

I hope you enjoyed the article and had a good learning experience.

Follow for more articles and keep sharingπŸ‘©

Keep coding

Python blogs

Linkedin

hashnode blogs

Did you find this article valuable?

Support akshita garg by becoming a sponsor. Any amount is appreciated!

Β