Getting Started
A. Installing Required Libraries (requests library)
– The `requests` library is a widely-used HTTP library for Python, designed to simplify the process of making HTTP requests from Python code.
– To install the `requests` library, use the following command in your terminal:
“`bash
pip install requests
“`
B. Understanding HTTP methods (GET, POST, PUT, DELETE)
– GET: Retrieves data from a specified resource.
– POST: Submits data to be processed to a specified resource.
– PUT: Updates data of a specified resource.
– DELETE: Deletes the specified resource.
C. Making your first API request
– Begin by importing the `requests` library into your Python script.
– Utilize the appropriate HTTP method function (`requests.get`, `requests.post`, `requests.put`, `requests.delete`) to send a request to the desired API endpoint.
– Process and handle the response returned by the API.
Examples of Publicly Available API Endpoints:
– [Random User Generator API](https://randomuser.me/api/)
– [The Cat API](https://api.thecatapi.com/)
Examples:
# Random User Generator API:
“`python
import requests
response = requests.get(“https://randomuser.me/api/”)
print(response.text)
“`
# The Cat API:
“`python
import requests
response = requests.get(“https://api.thecatapi.com/”)
print(response.text)
“`
Understanding Endpoints:
When you call the base URL of an API, you often receive a generic message providing basic information about the API, such as its name or version. Endpoints, on the other hand, specify the resource you want to access within the API. Well-documented APIs typically offer an API reference detailing available endpoints and their use cases.
# Example using The Cat API’s `/breeds` endpoint:
“`python
import requests
response = requests.get(“https://api.thecatapi.com/v1/breeds”)
print(response.text)
“`
HTTPS vs. HTTP:
It’s important to understand the difference between `http://` and `https://` endpoints. HTTPS encrypts all traffic between the client and the server, enhancing security. When consuming public APIs, prioritize using secure `https://` endpoints to safeguard sensitive information.
Request and Response:
All interactions between a client (e.g., Python console) and an API involve a request and a response:
– Request: Contains relevant data regarding the API call, such as the base URL, endpoint, method, and headers.
– Response: Contains relevant data returned by the server, including content, status code, and headers.
# Example accessing attributes of Request and Response objects:
“`python
import requests
response = requests.get(“https://api.thecatapi.com/v1/breeds”)
print(response.status_code)
print(response.text)
print(response.headers)
print(response.request.method)
print(response.request.url)
“`
Status Codes:
Status codes provide crucial information about API responses, indicating whether a request was successful, missing data, or encountered errors. Common status codes include:
– 200 OK: Successful request.
– 201 Created: Resource successfully created.
– 400 Bad Request: Incorrect or incomplete request.
– 401 Unauthorized: Additional permissions required.
– 404 Not Found: Requested resource not found.
– 500 Internal Server Error: Unexpected server error.
Understanding status codes is essential for interpreting API responses effectively.
You can check the status of a response using `.status_code` and `.reason`. The requests library also prints the status code in the representation of the Response object:
“`python
import requests
response = requests.get(“https://api.thecatapi.com/v1/breeds”)
print(response)
print(response.status_code)
print(response.reason)
“`
Your request returns 200, so you can consider it a successful request. But now have a look at a failing request triggered when you include a typo in the endpoint:
“`python
response = requests.get(“https://api.thecatapi.com/v1/breedz”)
print(response)
print(response.status_code)
print(response.reason)
“`
As you can see, the `/breedz` endpoint doesn’t exist, so the API returns a 404 Not Found status code.
You can use these status codes to quickly see if you need to change your request or check the documentation again for any typos or missing pieces.
HTTP Headers
HTTP headers can define a few parameters governing requests and responses:
| HTTP Header | Description |
|—————-|————————————————–|
| Accept | What type of content the client can accept |
| Content-Type | What type of content the server will respond with|
| User-Agent | What software the client is using |
| Server | What software the server is using |
| Authentication| Who’s calling the API and what credentials they have |
There are many other headers that you can find when inspecting a request or response. Have a look at Mozilla’s extended list if you’re curious about the specific use for each of them.
To inspect the headers of a response, you can use `response.headers`:
“`python
response = requests.get(“https://api.thecatapi.com/v1/breeds/abys”)
print(response.headers)
“`
To do the same with the request headers, you can use `response.request.headers` since request is an attribute of the Response object:
“`python
response = requests.get(“https://api.thecatapi.com/v1/breeds/abys”)
print(response.request.headers)
“`
In this case, you don’t define any specific headers when you make the request, so Python returns the default headers.
Custom Headers
Another standard that you might come across when consuming APIs is the use of custom headers. These usually start with `X-`, but that’s not a requirement. API developers typically use custom headers to send or request additional custom information from clients.
You can use a dictionary to define headers, and you can send them along with your request using the `headers` parameter of `.get()`.
For example, say you want to send some request ID to the API server, and you know you can do that using `X-Request-Id`:
“`python
headers = {“X-Request-Id”: “<my-request-id>”}
response = requests.get(“https://example.org”, headers=headers)
print(response.request.headers)
“`
If you go through the `request.headers` dictionary, then you’ll find `X-Request-Id` right at the end, among a few other headers that come by default with any API request.
A response might have many useful types of headers, but one of the most important ones is `Content-Type`, which defines the kind of content returned in the response.
Â
Â