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.
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 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.