![]() |
VOOZH | about |
API stands for "Application Programming Interface." In simple terms, it's a set of rules and protocols that allow how different software applications can communicate and interact with each other. APIs define the methods and data formats that applications can use to request and exchange information. To retrieve data from a web server, a client application initiates a request, and the server responds with the requested data.
APIs act as bridges that enable the smooth exchange of data and functionality, enhancing interoperability across various applications. Let's learn about how to work with APIs in Python
In order to work with APIs, some tools are required, such as requests module and we need to first install them in our system.
Command to install 'requests':
pip install requests
Once we have installed it, we need to import it in our code to use it.
Command to import 'requests':
import requests
Let us understand the working of API with examples. First let us take a simple example.
This example retrieves the latest opening price for IBM stock at a 5-minute interval from alphavantage api endpoint. Here we are using 'requests' to make a call and it is checked with the help of that whether our request was successful or not. Then the response is converted to python and the respected data is stored.
Output:
Explanation:
Status codes tell us how the server handled our request:
These codes help in debugging and managing API responses.
To fetch news, you often need an API key for authentication. Here’s how to get top business headlines from the US.
Explanation:
When working with APIs, understanding JSON is key because it’s the common format APIs use to send data. Think of JSON as the language APIs speak to share information like news headlines, images, and descriptions.
To handle this data, we use Python and the requests library to fetch news from NewsAPI. Then, Python helps organize and display the top articles clearly- like a helpful librarian sorting through lots of information for us. This shows how JSON and Python work together to make API data easy to use.
Note: For the below code to run, you need to get you own API credentials.
Output:
Article 1:
{
"author": "SamMobile, Asif Iqbal Shaik",
"content": "As tensions between China and the US escalate, the two countries are trying to counter each other through certain measures. The USA banned US-based chipmakers from exporting advanced chips and chip m\u2026 [+2001 chars]",
"description": "As tensions between China and the US escalate, the two countries are trying to counter each other through certain measures. ...",
"publishedAt": "2023-12-18T09:07:00Z",
"source": {
"id": null,
"name": "SamMobile"
},"title": "China bans Apple and Samsung phones from government offices and firms - SamMobile - Samsung news",
"url": "https://www.sammobile.com/news/china-bans-apple-iphone-samsung-phones-government-offices-firms/",
"urlToImage": "https://www.sammobile.com/wp-content/uploads/2023/08/Samsung-Galaxy-Z-Flip-5-Fold-5-China-720x405.jpg"
}
Explanation:
To learn about JSON format in detail refer to: JSON
When using an API like NewsAPI, it’s important to specify exactly what data you want. In this example, we fetch the top headlines for the United States. We use the API’s URL (API_URL) and provide our unique API key (API_KEY) for access.
But having just the URL and key isn’t enough. APIs let you customize your request with parameters. Here, we use a params dictionary to set the country to "us" and include our API key to authenticate the request.
Output
{
"status": "ok",
"totalResults": 37,
"articles": [
{
"source": {
"id": null,
"name": "BBC News"
},
"author": null,
"title": "Iceland volcano erupts on Reykjanes peninsula - BBC.com",
"description": "The eruption, in south-west Iceland, led to half the sky being \"lit up in red\", an eyewitness says.",
"url": "https://www.bbc.com/news/world-europe-67756413",
"urlToImage": "https://ichef.bbci.co.uk/news/1024/branded_news/13806/production/_132087897_helicopterstill.jpg",
"publishedAt": "2023-12-19T08:24:57Z",
"content": "By Marita Moloney & Oliver SlowBBC News\r\nSpectacular helicopter shots show the eruption on the island's coast\r\nA volcano has erupted on the Reykjanes peninsula of south-west Iceland after weeks o… [+5343 chars]"
}
]
}
Explanation:
This example uses several libraries to track ISS in real-time and map its position using Python’s turtle graphics.
So now there is a problem with tracking ISS because it travels at a speed of almost 28000km/h. Thus, it takes only 90 minutes to complete 1 rotation around the earth. At such a speed, it becomes quite difficult to lock the exact coordinates. So here comes the API to solve this issue. API acts as an intermediate between the website and the program, thus providing the current time data for the program.
In our case, API will provide us with the current location of ISS in earth’s orbit, so visit the link below as an API link for astronaut info.
url = "http://api.open-notify.org/astros.json"
Use urllib.request.urlopen() function inorder to open the API url and json.loads(.read()) function to read the data from the URL.
Output:
{"number": 10, "people": [{"craft": "ISS", "name": "Sergey Prokopyev"},
{"craft": "ISS", "name": "Dmitry Petelin"},
{"craft": "ISS", "name": "Frank Rubio"},
{"craft": "Tiangong", "name": "Jing Haiping"},
{"craft": "Tiangong", "name": "Gui Haichow"},
{"craft": "Tiangong", "name": "Zhu Yangzhu"},
{"craft": "ISS", "name": "Jasmin Moghbeli"},
{"craft": "ISS", "name": "Andreas Mogensen"},
{"craft": "ISS", "name": "Satoshi Furukawa"},
{"craft": "ISS", "name": "Konstantin Borisov"}], "message": "success"}
Explanation:
Opens API URL and reads JSON data.
Create iss.text file using an in write mode and write the result (names & numbers of astronauts) as data inside the file.
Use geocoder.ip(‘me’) to know your current location in terms of latitude and longitude.
Use turtle.screen() function to get access to the screen, then use screen.setup() to set the size and position of the output window. Use screen.setworldcoordinates() function to set the coordinates of all 4 corners on x, y-axis so that when iss reach out from reaches they appear again from another edge.
Explanation:
Access the current status of ISS using the API below:
url = "http://api.open-notify.org/iss-now.json"
Extract the current location of ISS in terms of latitude and longitude from the above API. This script below runs inside the while loop so you can see the updated position and movement of the ISS until you stop the program.
Explanation:
Below is the complete code implementation:
Output:
Crew Information: Here is info on the onboarded crew members along with their names.
ISS Location: Here is a screenshot of the moving ISS i.e orbiting around the earth. You can see it by zooming in on the screenshot.
ISS Moving look: Here you can see the ISS moving every 5 seconds.