HTTP requests

The Requests library is a popular Python library for making HTTP requests. It simplifies the process of sending HTTP requests and handling HTTP responses, making it easier for developers to interact with web services and APIs. Requests is widely used in the Python community and is known for its simplicity and ease of use.

Here are some key features and concepts related to the Requests library:

  • HTTP Methods: Requests supports various HTTP methods, including GET, POST, PUT, DELETE, and more. You can use these methods to interact with web resources based on your specific needs.
  • HTTP Headers: You can set custom headers in your HTTP requests, which is useful for passing information like authentication tokens, user agents, and content types.
  • URL Parameters: You can include URL parameters in your requests to send additional data to the server when making a GET request. The params parameter in the Requests library allows you to do this easily.
  • Request Data: When making POST or PUT requests, you can send data in the request body. Requests supports sending data as form data, JSON, or any other format you need.
  • Authentication: Requests supports various authentication methods, including Basic Authentication, OAuth, and API keys. You can set authentication credentials in your requests using built-in features.
  • Session Management: Requests allows you to create and manage sessions, which can be useful for persisting cookies and other session-related data across multiple requests to the same server.
  • Response Handling: You can easily access the response data, including the HTTP status code, headers, and content. Requests also provides convenient methods for parsing JSON and handling other common response formats.
  • Error Handling: Requests can raise exceptions for various HTTP errors, making it easy to handle errors gracefully in your code.

Python example

Let's use the "JSONPlaceholder" API as an example. JSONPlaceholder is a free fake online REST API for testing and prototyping. It provides various endpoints for typical CRUD (Create, Read, Update, Delete) operations on resources like posts, users, and comments. You can access this API at jsonplaceholder.typicode.com.

In this example, we'll make a GET request to retrieve a list of posts and then a POST request to create a new post using the Requests library in Python:

import requests

# Define the base URL for the JSONPlaceholder API
base_url = "https://jsonplaceholder.typicode.com"

# Perform a GET request to retrieve a list of posts
response = requests.get(f"{base_url}/posts")

# Check if the request was successful (status code 200)
if response.status_code == 200:
    # Parse the JSON response
    posts = response.json()
    print("List of posts:")
    for post in posts:
        print(f"Title: {post['title']}, ID: {post['id']}")
else:
    print("Failed to retrieve posts with status code:", response.status_code)

# Define a new post to create
new_post = {
    "userId": 1,
    "title": "New Post Title",
    "body": "This is the body of the new post."
}

# Perform a POST request to create a new post
post_response = requests.post(f"{base_url}/posts", json=new_post)

# Check if the post request was successful (status code 201)
if post_response.status_code == 201:
    created_post = post_response.json()
    print("\nNewly created post:")
    print(f"Title: {created_post['title']}, ID: {created_post['id']}")
else:
    print("Failed to create a new post with status code:", post_response.status_code)

In this example:

  • We perform a GET request to retrieve a list of posts from the JSONPlaceholder API.
  • If the GET request is successful (status code 200), we parse the JSON response and print the titles and IDs of the retrieved posts.
  • Then, we define a new post as a Python dictionary.
  • We perform a POST request to create a new post on the API, passing the new_post dictionary as JSON data.
  • If the POST request is successful (status code 201), we parse the JSON response and print the title and ID of the newly created post.

You can explore other API endpoints and perform various CRUD operations using the Requests library with the JSONPlaceholder API or any other API of your choice.