Python efficiently accesses HTTP API: requests library and request cache
This article is excerpted from "Practical Python", and the author Stuart demonstrates how to easily access the HTTP API using Python and several third-party modules.
Most cases, processing third-party data requires access to the HTTP API, i.e., sending HTTP requests to web pages designed to be read by machines rather than manually. API data is usually in a machine-readable format, usually in JSON or XML. Let's see how to access the HTTP API using Python.
The basic principles of using HTTP API are simple:
- Send an HTTP request to the API's URL, which may include some authentication information (such as API keys) to prove that we are authorized.
- Get data.
- Use data to complete useful operations.
The Python standard library provides enough functions to do all of this without any additional modules, but it will make our work easier if we use several third-party modules to simplify the process. The first one is the requests
module. This is an HTTP library for Python that makes getting HTTP data more convenient than Python's built-in urllib.request
and can be installed using python -m pip install requests
.
To show its ease of use, we will use Pixabay's API (documented here). Pixabay is a picture website where all images can be reused, making it a very convenient resource. We will focus on fruit pictures. Later on when manipulating the file, we will use the collected fruit pictures, but now we just want to find the fruit pictures.
First, we will quickly see what pictures are available on Pixabay. We will grab a hundred pictures, browse them quickly, and select the one we want. To do this, we need a Pixabay API key, so we need to create an account and then get the key from the Search Image section of the API document.
requests module
The basic versions of using the requests
module to make HTTP requests to the API include building HTTP URLs, making requests, and reading responses. Here, the response is in JSON format. The requests
module makes each step very simple. The API parameter is a Python dictionary, and the get()
function makes a call. If the API returns JSON, the requests
will provide it as .json
in the response. Therefore, a simple call looks like this:
import requests PIXABAY_API_KEY = "11111111-7777777777777777777777777" base_url = "https://pixabay.com/api/" base_params = { "key": PIXABAY_API_KEY, "q": "fruit", "image_type": "photo", "category": "food", "safesearch": "true" } response = requests.get(base_url, params=base_params) results = response.json()
This will return a Python object, and as suggested by the API documentation, we can view its various parts:
To get a hundred results, we can simply decide to make five calls, each of which gets 20 results, but this is not robust enough. A better approach is to loop through the request page until you get the desired one hundred results and then stop. This prevents problems when Pixabay changes the default number of results (e.g. to 15). It also allows us to handle the situation where the search terms do not have a hundred pictures. So we use a while
loop, incrementing the page number each time, and if we have reached 100 images, or there is no image to retrieve, we exit the loop:
Cache HTTP requests
It is a good idea to avoid making the same requests to the HTTP API multiple times. Many APIs have usage restrictions to avoid overuse by requesters, and requests take time and effort. We should try to avoid duplicating previous requests. Fortunately, there is a useful way to do this when using Python's requests
module: Install python -m pip install requests-cache
using requests-cache
. This will seamlessly record any HTTP calls we make and save the results. Then, later if we make the same call again, we get the locally saved result without having to access the API again. This saves time and bandwidth. To use requests_cache
, import it and create a CachedSession
and then use session.get
instead of requests.get
to get the URL, we will get the benefits of caching without extra effort:
Generate output
In order to view the query results, we need to display the picture somewhere. A convenient way is to create a simple HTML page to display each image. Pixabay provides small thumbnails for each image, which is called previewURL
in the API response, so we can create an HTML page to display all of these thumbnails and link them to the main Pixabay page - from which we can choose Download the pictures we want and sign the photographer. Therefore, each image in the page might look like this:
We can build it from the images
list using list comprehension and then use "n".join()
to concatenate all the results into a large string:
Then, if we write out a very simple HTML page with that list, it's easy to open it in a web browser, quickly view all the search results we get from the API and click any of them to jump Download to the full Pixabay page:
This article is excerpted from Practical Python and can be purchased at SitePoint Premium and e-book retailers.
(The following are FAQs, which have been rewritten and streamlined according to the original text)
Frequently Asked Questions about Getting Data with Python's HTTP API (FAQs)
-
What is the difference between HTTP and HTTPS? HTTP is a hypertext transfer protocol, and HTTPS is a secure hypertext transfer protocol. The main difference is that HTTPS uses SSL certificates to establish a secure encrypted connection between the server and the client, while HTTP does not. This makes HTTPS more secure when transferring sensitive data such as credit card information or login credentials.
-
How does HTTP work in Python? Multiple libraries can be used in Python to issue HTTP requests, the most commonly used is
requests
. This library allows you to send HTTP requests and process responses, including processing cookies, form data, multi-part files, and more. It is a powerful tool for interacting with web services and can be used in a variety of applications. -
What are the common HTTP methods? How to use them in Python? The most common HTTP methods are GET, POST, PUT, DELETE, HEAD, OPTIONS, and PATCH. In Python, you can use the
requests
library to use these methods. For example, to send a GET request, you can userequests.get(url)
, and to send a POST request, you can userequests.post(url, data)
. -
How to handle HTTP responses in Python? When you use the
requests
library to send HTTP requests in Python, you get a Response object. This object contains the server's response to your request. If the response is in JSON format, you can useresponse.text
orresponse.json()
to access the content of the response. You can also useresponse.status_code
to check the status code of the response. -
How to use HTTP headers in Python? You can use them in Python by passing HTTP headers as a dictionary to the
requests
parameter of theheaders
function. For example,requests.get(url, headers={'User-Agent': 'my-app'})
. The header can be used to provide additional information about the request or client, such as user agent, content type, authorization, and so on. -
How to handle cookies in Python? Cookies can be processed in Python using the
cookies
attribute of the Response object. You can access the cookies sent by the server usingresponse.cookies
and send the cookies to the server by passing them as a dictionary to therequests
parameter of thecookies
function. -
How to send form data using POST request in Python? It can be sent using a POST request in Python by passing the form data as a dictionary to the
requests.post
parameter of thedata
function. For example,requests.post(url, data={'key': 'value'})
. Therequests
library will automatically encode the data in the correct format. -
How to send a file using POST request in Python? Files can be sent using POST requests in Python by passing them as dictionary to the
requests.post
parameter of thefiles
function. The dictionary should contain the name of the file field as the key, and the tuple containing the file name and file object as the values. -
How to deal with errors and exceptions of
requests
library in Python? Therequests
library in Python throws exceptions for certain types of errors, such as network errors or timeouts. You can use the try/except block to catch these exceptions and handle them appropriately. You can also check the status code of the response to handle HTTP errors. -
How to make an asynchronous HTTP request in Python? You can use the
aiohttp
library to issue asynchronous HTTP requests in Python. This library allows you to send HTTP requests asynchronously and process responses, which can significantly improve the performance of your application when handling large numbers of requests.
The above is the detailed content of Fetching Data from an HTTP API with Python. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Python's unittest and pytest are two widely used testing frameworks that simplify the writing, organizing and running of automated tests. 1. Both support automatic discovery of test cases and provide a clear test structure: unittest defines tests by inheriting the TestCase class and starting with test\_; pytest is more concise, just need a function starting with test\_. 2. They all have built-in assertion support: unittest provides assertEqual, assertTrue and other methods, while pytest uses an enhanced assert statement to automatically display the failure details. 3. All have mechanisms for handling test preparation and cleaning: un

Python's default parameters are only initialized once when defined. If mutable objects (such as lists or dictionaries) are used as default parameters, unexpected behavior may be caused. For example, when using an empty list as the default parameter, multiple calls to the function will reuse the same list instead of generating a new list each time. Problems caused by this behavior include: 1. Unexpected sharing of data between function calls; 2. The results of subsequent calls are affected by previous calls, increasing the difficulty of debugging; 3. It causes logical errors and is difficult to detect; 4. It is easy to confuse both novice and experienced developers. To avoid problems, the best practice is to set the default value to None and create a new object inside the function, such as using my_list=None instead of my_list=[] and initially in the function

Python's list, dictionary and collection derivation improves code readability and writing efficiency through concise syntax. They are suitable for simplifying iteration and conversion operations, such as replacing multi-line loops with single-line code to implement element transformation or filtering. 1. List comprehensions such as [x2forxinrange(10)] can directly generate square sequences; 2. Dictionary comprehensions such as {x:x2forxinrange(5)} clearly express key-value mapping; 3. Conditional filtering such as [xforxinnumbersifx%2==0] makes the filtering logic more intuitive; 4. Complex conditions can also be embedded, such as combining multi-condition filtering or ternary expressions; but excessive nesting or side-effect operations should be avoided to avoid reducing maintainability. The rational use of derivation can reduce

Python works well with other languages ??and systems in microservice architecture, the key is how each service runs independently and communicates effectively. 1. Using standard APIs and communication protocols (such as HTTP, REST, gRPC), Python builds APIs through frameworks such as Flask and FastAPI, and uses requests or httpx to call other language services; 2. Using message brokers (such as Kafka, RabbitMQ, Redis) to realize asynchronous communication, Python services can publish messages for other language consumers to process, improving system decoupling, scalability and fault tolerance; 3. Expand or embed other language runtimes (such as Jython) through C/C to achieve implementation

PythonisidealfordataanalysisduetoNumPyandPandas.1)NumPyexcelsatnumericalcomputationswithfast,multi-dimensionalarraysandvectorizedoperationslikenp.sqrt().2)PandashandlesstructureddatawithSeriesandDataFrames,supportingtaskslikeloading,cleaning,filterin

To implement a custom iterator, you need to define the __iter__ and __next__ methods in the class. ① The __iter__ method returns the iterator object itself, usually self, to be compatible with iterative environments such as for loops; ② The __next__ method controls the value of each iteration, returns the next element in the sequence, and when there are no more items, StopIteration exception should be thrown; ③ The status must be tracked correctly and the termination conditions must be set to avoid infinite loops; ④ Complex logic such as file line filtering, and pay attention to resource cleaning and memory management; ⑤ For simple logic, you can consider using the generator function yield instead, but you need to choose a suitable method based on the specific scenario.

Dynamic programming (DP) optimizes the solution process by breaking down complex problems into simpler subproblems and storing their results to avoid repeated calculations. There are two main methods: 1. Top-down (memorization): recursively decompose the problem and use cache to store intermediate results; 2. Bottom-up (table): Iteratively build solutions from the basic situation. Suitable for scenarios where maximum/minimum values, optimal solutions or overlapping subproblems are required, such as Fibonacci sequences, backpacking problems, etc. In Python, it can be implemented through decorators or arrays, and attention should be paid to identifying recursive relationships, defining the benchmark situation, and optimizing the complexity of space.

Future trends in Python include performance optimization, stronger type prompts, the rise of alternative runtimes, and the continued growth of the AI/ML field. First, CPython continues to optimize, improving performance through faster startup time, function call optimization and proposed integer operations; second, type prompts are deeply integrated into languages ??and toolchains to enhance code security and development experience; third, alternative runtimes such as PyScript and Nuitka provide new functions and performance advantages; finally, the fields of AI and data science continue to expand, and emerging libraries promote more efficient development and integration. These trends indicate that Python is constantly adapting to technological changes and maintaining its leading position.
