Simplified HTTP REST Client

3.3.7 · active · verified Sun Mar 29

python-http-client is a simplified HTTP REST client library for Python, providing an easy-to-use interface for interacting with RESTful APIs. It is currently at version 3.3.7 and maintains an active release cadence with regular updates and fixes, often associated with Twilio SendGrid's services.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize the `Client` with a base host and optional headers, then construct and execute a GET and POST request to a generic API endpoint using its dynamic path building and HTTP verb methods. It includes placeholders for API host and key, ideally read from environment variables.

import os
from python_http_client import Client

# Replace with your actual API host (e.g., "https://api.example.com")
# Using httpbin.org for a simple example.
HOST = os.environ.get('API_HOST', 'https://httpbin.org')
API_KEY = os.environ.get('API_KEY', '') # For APIs requiring authorization

def make_request():
    try:
        # Instantiate the client with base host and optional headers
        # For an API like SendGrid, 'version' might be a parameter.
        client = Client(host=HOST, request_headers={
            "Authorization": f"Bearer {API_KEY}"
        } if API_KEY else {}) 

        # Example: GET request to /get endpoint
        # The _() method adds path segments dynamically
        # .get() performs the GET request
        print(f"\nMaking GET request to {HOST}/get")
        response = client._('get').get()

        print(f"GET Status Code: {response.status_code}")
        print(f"GET Response Body: {response.to_dict()}")

        # Example: POST request to /post endpoint with data
        data = {"message": "Hello from python-http-client!"}
        print(f"\nMaking POST request to {HOST}/post with body: {data}")
        post_response = client._('post').post(request_body=data)

        print(f"POST Status Code: {post_response.status_code}")
        print(f"POST Response Body: {post_response.to_dict()}")

    except Exception as e:
        print(f"An error occurred: {e}")

if __name__ == "__main__":
    make_request()

view raw JSON →