import json
import time
import requests
def validate_json_with_retry(url, payload, max_retries=3, retry_delay=1):
"""
Validates a JSON payload against a URL with retry logic.
Args:
url (str): The URL to send the payload to for validation.
payload (dict): The JSON payload to validate.
max_retries (int): The maximum number of retry attempts.
retry_delay (int): The delay in seconds between retries.
Returns:
bool: True if the validation is successful, False otherwise.
"""
for attempt in range(max_retries):
try:
# Send the payload to the URL
response = requests.post(url, json=payload)
response.raise_for_status() # Raise HTTPError for bad responses (4xx or 5xx)
# If we reach here, the request was successful
return True
except requests.exceptions.RequestException as e:
print(f"Attempt {attempt + 1} failed: {e}")
if attempt < max_retries - 1:
print(f"Retrying in {retry_delay} seconds...")
time.sleep(retry_delay)
else:
print("Validation failed after multiple retries.")
return False
except json.JSONDecodeError as e:
print(f"Error decoding JSON response: {e}")
return False
if __name__ == '__main__':
# Example Usage
url = "https://your-validation-endpoint.com/validate" # Replace with your validation endpoint
payload = {"key1": "value1", "key2": 123}
if validate_json_with_retry(url, payload):
print("Validation successful!")
else:
print("Validation failed.")
Add your comment