How to make API calls in Python
Information is extremely critical these days since it drives applications and organizations. It is subsequently critical to figure out how to get this information to serve your application. In fundamental terms, an API resembles a channel that permits applications to speak with each other.
Make your API decision
There are various ways of bringing information in Python. For this post, we will involve the solicitations module in Python. The solicitations module is a basic yet rich HTTP library. To introduce this library, utilize the accompanying order:
pip introduce requests
To really look at the introduced form, utilize the accompanying order:
pip freeze | grep requests
requests==2.22.0
Seems as though your current circumstance is presently prepared to toss a few solicitations.
def get_data(self, api):
response = requests.get(f"{api}")
if response.status_code == 200:
print("successfully fetched the data")
self.formatted_print(response.json())
else:
print(f"Hello person, there's a {response.status_code} error with your request")
As seen above, we first check the status code and afterwards print the information. This code informs us regarding the reaction that has been gotten in view of our solicitations. The 200 code lets us know that we have gotten the data effectively. Numerous codes demonstrate various reactions, as displayed underneath:
Code | Status | Description |
200 | Ok | The solicitation was finished. |
201 | Created | Another asset was effectively made. |
400 | Bad Request | The request was invalid |
401 | Unauthorized | The solicitation did exclude a verification token, or the confirmation token was terminated. |
403 | Forbidden | The client didn't have the authorization to get to the mentioned asset. |
404 | Not found | The mentioned asset was not found. |
405 | Method not allowed | The HTTP technique in the solicitation was not upheld by the asset. For instance, the DELETE strategy can't be utilized with the Agent API. |
409 | Conflict | The solicitation couldn't be finished because of contention. For instance, POST ContentStore Folder API can't finish assuming the given document or envelope name as of now exists in the parent area. |
500 | Internal server error | The solicitation was not finished because of an inside blunder on the server side. |
503 | Service Unavailable | The server was unavailable |
Essentially, we can likewise settle on the API decision for certain boundaries. For this situation, we should get articles from a specific client: me.
boundaries = {
"username": "kedark"
}
I have put away the boundaries in a variable; presently, we should settle on an API decision with similar parameters.
def get_user_data(self, api, parameters):
response = requests.get(f"{api}", params=parameters)
if response.status_code == 200:
print("sucessfully fetched the data with parameters provided")
self.formatted_print(response.json())
else:
print(
f"Hello person, there's a {response.status_code} error with your request")
API Documentation
To guarantee we make a fruitful solicitation, when we work with APIs counselling, the documentation is significant. Documentation can appear to be startling from the get-go, yet as you use documentation increasingly more, you'll find it gets simpler. We'll be working with the Open Notify API, which gives admittance to information about the worldwide space station. It's an extraordinary API for learning since it has an exceptionally straightforward plan and doesn't need confirmation. We'll show you how to involve an API that requires validation in a later post. Frequently there will be numerous APIs accessible on a specific server. Every one of these APIs are ordinarily called endpoints.
The principal endpoint we'll utilize is http://api.open-notify.org/astros.json, which returns information about space explorers presently in space. Assuming you click the connection above to take a gander at the documentation for this endpoint, you'll see that it says This API takes no data sources. This makes it a straightforward API for us to begin with. We'll begin by making a GET solicitation to the endpoint utilizing the solicitations library:
response = requests.get("https://api.open-notify.org/astros.json")
print(response.status_code)
Output

Working with JSON Data in Python
JSON (JavaScript Object Notation) is the language of APIs. JSON is a method for encoding information structures that guarantees that they are effectively coherent by machines. JSON is the essential configuration wherein information is passed this way and that to APIs, and most API servers will send their reactions in JSON design. You could have seen that the JSON yield we got from the API seemed as though it contained Python word references, records, strings and numbers. You can consider JSON to be a mix of these items addressed as strings.
Python has incredible JSON support with the json bundle. The json bundle is essential for the standard library, so we don't need to introduce anything to utilize it. We can both believer records and word references to JSON and convert strings to records and word references. On account of our ISS Pass information, it is a word reference encoded to a string in JSON design. The json library has two primary capabilities:
json.dumps() — Takes in a Python item and converts (dumps) it to a string.
json.loads() — Takes a JSON string and converts (loads) it to a Python object.
Example
import json
def jprint(obj):
# create a formatted string of the Python JSON object
text = json.dumps(obj, sort_keys=True, indent=4)
print(text)
jprint(response.json())
Output
