Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0613· OpenAIHugging Face Arena Human Preference 55K

generate python code to invoke a REST API

  1. User

    generate python code to invoke a REST API

  2. Assistant

    Sure! Here's an example of Python code to invoke a REST API using the requests library:

    import requests
    
    # Set the API endpoint URL
    url = "https://api.example.com/endpoint"
    
    # Set the request headers (if required)
    headers = {
        "Content-Type": "application/json",
        "Authorization": "Bearer YOUR_ACCESS_TOKEN"
    }
    
    # Set the request payload (if required)
    payload = {
        "param1": "value1",
        "param2": "value2"
    }
    
    # Send a GET request
    response = requests.get(url, headers=headers, params=payload)
    
    # Send a POST request
    # response = requests.post(url, headers=headers, json=payload)
    
    # Send a PUT request
    # response = requests.put(url, headers=headers, json=payload)
    
    # Send a DELETE request
    # response = requests.delete(url, headers=headers)
    
    # Check the response status code
    if response.status_code == 200:
        # Successful request
        print("Request successful!")
        print(response.json())
    else:
        # Failed request
        print("Request failed!")
        print("Status code:", response.status_code)
        print("Response:", response.text)
    

    You can uncomment the appropriate request method (GET, POST, PUT, or DELETE) based on the API you want to invoke. Remember to replace the url, headers, and payload with your own values.