API call in Python

API call in Python

API stands for Application Programming Interface.

In Simple words, it’s an interface which allows websites to exchange/expose data within different websites or anyone requesting the API.

API are hosted on servers, when a application calls the API it returns data based on the ‘endpoint’.

Typically API responses are in JSON format. (Read and Write JSON file in python)

Accessing a Simple “no auth” API:

A simple no auth API is a simple web address which requires no authentication and returns a JSON response when called.

For the example we will be using the https://jsonplaceholder.typicode.com/ prebuilt API.

API may have endpoints to access a section of data.

The Jsonplaceholder API has these endpoints.

/posts100 posts
/comments500 comments
/albums100 albums
/photos5000 photos
/todos200 todos
/users10 users

Lets write the code to access /posts endpoint of jsonplaceholder api.

To call the web address we will use the “request” package of python

Saving– Convert JSON list/dict response to string using json package and write it to a .json file.

import json
  #import json package
import requests
 #import requests package

response = requests.get(api_endpoint)

#print status code 200 if success

 #access the json part of the full response

# for i in data_json:
   #uncomment to print every entry in json file
# 	print(i)

 #convert list to string

 #opens or create file "apires.json" in same folder

  #write the string to file

file.close()  #close file to save file

Try to access the /user endpoint or only the 50th post in /post api

Read the full documentation of API HERE.

Thank you for reading, Happy Learning, drop your suggestion in the comments.

Feel free to follow us on Youtube, Linked In , Instagram

Loading comments...