Python调用Just-Eat API遇403错误及JSON解析失败求助
Hey there! Let's figure out why your API call is suddenly failing with a 403 status code and JSONDecodeError, especially since it worked before.
First, let's clarify the root of the JSONDecodeError: when you get a 403, the server isn't returning valid JSON (it's probably returning an HTML error page or a plain-text forbidden message). That's why response.json() throws an error—you're trying to parse non-JSON content as JSON.
Now, let's break down the likely causes and fixes:
Common Reasons for 403 Forbidden
Missing Required Request Headers
Many APIs (including Just-Eat's) expect specific headers to verify that the request is coming from a legitimate client. It's possible the server recently tightened its validation, and your barerequests.get()call no longer meets the requirements. The most common missing header is aUser-Agentthat mimics a browser.IP Rate Limiting/Block
If you made multiple requests in a short period, you might have triggered the API's anti-scraping or rate-limiting protections, resulting in a temporary IP block.API Authentication Changes
While the public docs might not explicitly state it, some APIs require an API key or token for access, even if they worked without it before. It's worth double-checking the documentation for any hidden authentication requirements.
Step-by-Step Fixes
Add Request Headers
Start by adding aUser-Agentheader to mimic a browser request. Here's how to update your code:import requests headers = { "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36" } response = requests.get( "https://uk.api.just-eat.io/restaurants/bypostcode/NW32YT", headers=headers ) # First check the status code and raw response text to debug print(f"Status Code: {response.status_code}") print("Response Text:", response.text) # Only parse JSON if the request succeeded if response.status_code == 200: print(response.json())This should resolve the 403 if the issue was a missing header.
Check for Rate Limits
If adding headers doesn't work, try waiting a few minutes before making another request. If it starts working again, you'll know you hit a rate limit. Consider adding delays between requests if you're making multiple calls.Verify Authentication Requirements
Re-review the Just-Eat API docs to see if there's any mention of API keys or authentication tokens. Some APIs require these in headers (e.g.,Authorization: Bearer YOUR_TOKENorApi-Key: YOUR_KEY) even if they weren't required initially.
Why It Worked Before
The most likely scenario is that the Just-Eat API updated its security rules—maybe they started enforcing User-Agent checks, or their rate-limiting thresholds changed. APIs often tweak these settings without updating public docs immediately.
内容的提问来源于stack exchange,提问作者Mari

