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.
/posts | 100 posts |
/comments | 500 comments |
/albums | 100 albums |
/photos | 5000 photos |
/todos | 200 todos |
/users | 10 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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
import json #import json package import requests #import requests package api_endpoint="https://jsonplaceholder.typicode.com/posts" response = requests.get(api_endpoint) print(response.status_code) #print status code 200 if success data_json=response.json() #access the json part of the full response # for i in data_json: #uncomment to print every entry in json file # print(i) jsontostring=json.dumps(data_json) #convert list to string file=open("apires.json",'w') #opens or create file "apires.json" in same folder file.write(jsontostring) #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.
[…] APIs and using them in your application has become an inevitable task to make your application more modular and the development process […]