Skip to content

Call Any API from RapidAPI

🔑 ID:

28731

👨‍💻

Python

🕒

22/02/2024
Free

Description:

This is a function you can use to call any API published o rapidAPI from your code. Simply, enter the inputs needed and you’re all set!

Code:

import requests

def call_api(endpoint_url, HTTP_method, api_key=None, params=None):

    """
    endpoint: The API endpoint URL
    method: The HTTP method (e.g., 'GET', 'POST')
    API_key
    params: A dictionary of parameters to be sent 
    headers: A dictionary of HTTP headers to send with the request
    """
    
    # RapidAPI requires the API key to be included in the header with specific key name
    headers = {
        'x-rapidapi-key': api_key,
        'x-rapidapi-host': endpoint_url.split('/')[2] 
    }
    
    try:
        if HTTP_method.upper() == 'GET':
            response = requests.get(endpoint_url, headers=headers, params=params)
        elif HTTP_method.upper() == 'POST':
            response = requests.post(endpoint_url, headers=headers, json=params)
        else:
            return {'error': 'Unsupported method. Please use GET or POST.'}
        
        response.raise_for_status()
        return response.json()
    except requests.exceptions.RequestException as e:
        return {'error': str(e)}

result = call_api(
    "API_ENDPOINT",
    "GET",
    "YOUR_API_KEY,  
    params={"url": "PAGE_URL"}
)

print(result)

 

GitHub Link

✖️ Not Available

Download File

✖️ Not Available

If you’re encountering any problems or need further assistance with this code, we’re here to help! Join our community on the forum or Discord for support, tips, and discussion.