如何使用Python Requests库正确调用Cortical.io API?
I spot a few key issues that are likely causing your API call to fail—let's walk through fixing them:
1. Wrong HTTP Method
The Cortical.io similar_terms endpoint expects a POST request, not GET. GET requests are designed for retrieving data without sending structured payloads like your positions array; POST is the right choice here for passing JSON data in the request body.
2. Misplaced Parameters
You’re passing the positions array as URL query parameters (via the params argument), but this data needs to be sent in the JSON request body instead. URL query parameters aren’t meant for complex structured data like arrays.
3. URL Encoding Quirk
Your URL uses & instead of plain &—while Requests can sometimes handle this, it’s cleaner to replace those with regular ampersands to avoid unexpected encoding glitches.
Corrected Code
import requests # Replace with your actual API key api_key = "YOUR_ACTUAL_API_KEY_HERE" url = "http://api.cortical.io:80/rest/expressions/similar_terms?retina_name=en_associative&start_index=0&max_results=1&sparsity=1.0&get_fingerprint=false" # The positions payload belongs in the JSON request body payload = {"positions": [0, 6, 7, 29]} headers = {"api-key": api_key} # Use POST instead of GET, and pass the payload via the `json` argument response = requests.post(url, json=payload, headers=headers) # Add basic debugging to check results if response.status_code == 200: print("Success! Response:", response.json()) else: print(f"Error: {response.status_code}") print("Response details:", response.text)
Quick Notes
- When using
requests.post()with thejsonparameter, Requests automatically sets theContent-Type: application/jsonheader for you—so you don’t need to include it explicitly in your headers. - Checking the response status code and raw content is critical for debugging if things still go wrong—this will show you issues like invalid API keys, malformed payloads, or endpoint-specific errors.
内容的提问来源于stack exchange,提问作者MetaStack

