如何从Udemy API请求数据?获取课程列表时遇权限错误的技术咨询
Hey there! Let's break down why you're hitting that permission error and how to fix it to get the course list + URLs you need.
The Core Issue: Incorrect Authentication Flow
Udemy's API doesn't accept direct Basic Auth for course data endpoints. Instead, you need to first request an access token using your client ID and secret, then use that token for subsequent API calls. Your current code skips this critical token step, which is why you're getting the permission denied message. Also, since the API returns JSON data, you don't need BeautifulSoup—you can parse the response directly with Python's built-in JSON handling.
Step-by-Step Fix
1. First, Fetch an Access Token
Use your client ID and secret to get a valid access token from Udemy's token endpoint:
import requests client_id = "your_client_id" client_secret = "your_client_secret" # Request access token via client credentials flow token_response = requests.post( "https://www.udemy.com/api-2.0/oauth/token", data={ "grant_type": "client_credentials", "client_id": client_id, "client_secret": client_secret } ) # Handle token request errors if token_response.status_code != 200: print(f"Failed to retrieve token: {token_response.json()}") exit() access_token = token_response.json()["access_token"]
2. Use the Token to Fetch Courses & URLs
Now use the access token in the Authorization header (as a Bearer token) to call the courses endpoint. We'll parse the JSON response to extract course titles and their full URLs:
# Set up headers with the access token headers = { "Accept": "application/json", "Authorization": f"Bearer {access_token}" } # Fetch the filtered course list courses_response = requests.get( "https://www.udemy.com/api-2.0/courses/?page=1&page_size=10&search=python", headers=headers ) # Handle course request errors if courses_response.status_code != 200: print(f"Failed to retrieve courses: {courses_response.json()}") exit() # Extract and print course titles + full URLs courses = courses_response.json()["results"] for course in courses: print(f"Course Title: *{course['title']}*") full_course_url = f"https://www.udemy.com{course['url']}" print(f"Course URL: {full_course_url}\n")
Additional Notes
- Double-check your Udemy API application's scopes—if you still get permission errors after using the token, ensure your app is authorized to access course data.
- The
urlfield in the course object is a relative path, so we prependhttps://www.udemy.comto get the full, usable URL. - For production code, avoid hardcoding your client ID/secret—use environment variables to keep sensitive data secure.
内容的提问来源于stack exchange,提问作者Hamici Mossab

