search
HomeBackend DevelopmentPython TutorialFetching Data from an HTTP API with Python

Fetching Data from an HTTP API with Python

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:

  1. 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.
  2. Get data.
  3. 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:

Fetching Data from an HTTP API with Python

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 use requests.get(url), and to send a POST request, you can use requests.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 use response.text or response.json() to access the content of the response. You can also use response.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 the headers 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 using response.cookies and send the cookies to the server by passing them as a dictionary to the requests parameter of the cookies 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 the data function. For example, requests.post(url, data={'key': 'value'}). The requests 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 the files 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? The requests 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!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The Main Purpose of Python: Flexibility and Ease of UseThe Main Purpose of Python: Flexibility and Ease of UseApr 17, 2025 am 12:14 AM

Python's flexibility is reflected in multi-paradigm support and dynamic type systems, while ease of use comes from a simple syntax and rich standard library. 1. Flexibility: Supports object-oriented, functional and procedural programming, and dynamic type systems improve development efficiency. 2. Ease of use: The grammar is close to natural language, the standard library covers a wide range of functions, and simplifies the development process.

Python: The Power of Versatile ProgrammingPython: The Power of Versatile ProgrammingApr 17, 2025 am 12:09 AM

Python is highly favored for its simplicity and power, suitable for all needs from beginners to advanced developers. Its versatility is reflected in: 1) Easy to learn and use, simple syntax; 2) Rich libraries and frameworks, such as NumPy, Pandas, etc.; 3) Cross-platform support, which can be run on a variety of operating systems; 4) Suitable for scripting and automation tasks to improve work efficiency.

Learning Python in 2 Hours a Day: A Practical GuideLearning Python in 2 Hours a Day: A Practical GuideApr 17, 2025 am 12:05 AM

Yes, learn Python in two hours a day. 1. Develop a reasonable study plan, 2. Select the right learning resources, 3. Consolidate the knowledge learned through practice. These steps can help you master Python in a short time.

Python vs. C  : Pros and Cons for DevelopersPython vs. C : Pros and Cons for DevelopersApr 17, 2025 am 12:04 AM

Python is suitable for rapid development and data processing, while C is suitable for high performance and underlying control. 1) Python is easy to use, with concise syntax, and is suitable for data science and web development. 2) C has high performance and accurate control, and is often used in gaming and system programming.

Python: Time Commitment and Learning PacePython: Time Commitment and Learning PaceApr 17, 2025 am 12:03 AM

The time required to learn Python varies from person to person, mainly influenced by previous programming experience, learning motivation, learning resources and methods, and learning rhythm. Set realistic learning goals and learn best through practical projects.

Python: Automation, Scripting, and Task ManagementPython: Automation, Scripting, and Task ManagementApr 16, 2025 am 12:14 AM

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

Python and Time: Making the Most of Your Study TimePython and Time: Making the Most of Your Study TimeApr 14, 2025 am 12:02 AM

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python: Games, GUIs, and MorePython: Games, GUIs, and MoreApr 13, 2025 am 12:14 AM

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment