Python HTTP Requests Using `requests` Library

Introduction

In Python, the requests library is a popular tool for making HTTP requests. It provides a simple API for interacting with web servers to retrieve, send, update, or delete data.

This guide will demonstrate how to perform various HTTP request methods using the requests library, such as GET, POST, PUT, and DELETE.

Installing the Requests Library

To use the requests library, you first need to install it. You can do this with the following command:

pip install requests

Once installed, you can import it into your Python code:

import requests

Examples of Basic HTTP Requests

Here are some examples to showcase how different types of HTTP requests can be made using requests:

1. Making a GET Request

Retrieve data from a server using the GET method:

2. Making a POST Request

Send data to a server (e.g., submitting a form):

3. Making a PUT Request

Update an existing resource on a server:

4. Making a DELETE Request

Delete a resource from a server:

Working with Request Headers

You can add custom headers to your HTTP requests using the headers parameter:

Error Handling and Response Validation

Always check the status code to ensure a request was successful. In the example below:

  • The status_code of the response is checked to confirm if the request succeeded (200 OK).
  • If the response is successful (status_code == 200), the data is printed in JSON format.
  • If the request fails (e.g., other status codes like 404 or 500), the failure status code is displayed.

This provides a simple way to validate and handle HTTP responses effectively.

Summary

With the requests library, you can efficiently make HTTP requests in Python. It simplifies interaction with web servers, allowing you to easily handle GET, POST, PUT, DELETE, and other HTTP methods.

Co funded by the EU

Funded by the European Union. Views and opinions expressed are however those of the author(s) only and do not necessarily reflect those of the European Union or the European Education and Culture Executive Agency (EACEA). Neither the European Union nor EACEA can be held responsible for them.

Project Number: 2023-3-CY02-KA210-YOU-000173087