Middle
How to implement wait for API?
sobes.tech AI
Answer from AI
API testing uses explicit condition-based waits. The most common methods:
-
Polling: Periodic requests to the API until the expected result is received or the timeout expires.
import time import requests def wait_for_status(url, expected_status, timeout=30, interval=1): """ Waits for a specific status from the API. Args: url: API endpoint URL. expected_status: Expected HTTP status code. timeout: Maximum wait time in seconds. interval: Interval between attempts in seconds. Returns: requests.Response: Response object on success, None on timeout. """ start_time = time.time() while time.time() - start_time < timeout: try: response = requests.get(url) # Or another HTTP method if response.status_code == expected_status: return response except requests.exceptions.RequestException as e: print(f"Request error: {e}") # Logging request error time.sleep(interval) return None # Return None on timeout # Usage example # api_url = "http://example.com/api/resource" # expected_status_code = 200 # response = wait_for_status(api_url, expected_status_code) # if response: # print("Expected status received!") # else: # print("Status wait timeout.") -
Long polling: The client sends a request and the server keeps the connection open until data appears or the server timeout occurs. Less common in standard REST APIs, more used in event-driven architectures or WebSocket.
-
Webhooks: The API calls a specified URL on the client side when a certain event occurs. Requires a publicly accessible endpoint on the client side to receive the webhook.
- Implementation:
- Registering the webhook URL via another service's API.
- Writing client-side code to receive and process HTTP POST requests from the webhook.
- Waiting (usually asynchronously) to receive data via the webhook.
- Implementation:
The choice of method depends on the API architecture and testing requirements. Polling is the most common and simplest to implement for most REST APIs.