Skip to lesson content

API & Data · Lesson 15 of 17

Python HTTP Requests Using `requests` Library

Introduction

Fetch, send, update and delete data with examples you can run in Python.

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.