1. import json
  2. import time
  3. import requests
  4. def validate_json_with_retry(url, payload, max_retries=3, retry_delay=1):
  5. """
  6. Validates a JSON payload against a URL with retry logic.
  7. Args:
  8. url (str): The URL to send the payload to for validation.
  9. payload (dict): The JSON payload to validate.
  10. max_retries (int): The maximum number of retry attempts.
  11. retry_delay (int): The delay in seconds between retries.
  12. Returns:
  13. bool: True if the validation is successful, False otherwise.
  14. """
  15. for attempt in range(max_retries):
  16. try:
  17. # Send the payload to the URL
  18. response = requests.post(url, json=payload)
  19. response.raise_for_status() # Raise HTTPError for bad responses (4xx or 5xx)
  20. # If we reach here, the request was successful
  21. return True
  22. except requests.exceptions.RequestException as e:
  23. print(f"Attempt {attempt + 1} failed: {e}")
  24. if attempt < max_retries - 1:
  25. print(f"Retrying in {retry_delay} seconds...")
  26. time.sleep(retry_delay)
  27. else:
  28. print("Validation failed after multiple retries.")
  29. return False
  30. except json.JSONDecodeError as e:
  31. print(f"Error decoding JSON response: {e}")
  32. return False
  33. if __name__ == '__main__':
  34. # Example Usage
  35. url = "https://your-validation-endpoint.com/validate" # Replace with your validation endpoint
  36. payload = {"key1": "value1", "key2": 123}
  37. if validate_json_with_retry(url, payload):
  38. print("Validation successful!")
  39. else:
  40. print("Validation failed.")

Add your comment