我正在做一个项目,该项目调用YouTube API,将喜欢的视频中的歌曲导入到Spotify播放列表中。
在MacOS终端中使用YouTube数据API v3运行程序时遇到此问题。它显示了此错误代码。
exceptions.ResponseException: Response gave status code 400
我的终点是: https://api.spotify.com/v1/users/{user_id}/playlists
HTTP方法: POST
这是我的可执行代码:
import json
import os
import google_auth_oauthlib.flow
import googleapiclient.discovery
import googleapiclient.errors
import requests
import youtube_dl
from exceptions import ResponseException
from secrets import spotify_token, spotify_user_id
class CreatePlaylist:
def __init__(self):
self.youtube_client = self.get_youtube_client()
self.all_song_info = {}
def get_youtube_client(self):
""" Log Into Youtube, Copied from Youtube Data API """
# Disable OAuthlib's HTTPS verification when running locally.
# *DO NOT* leave this option enabled in production.
os.environ["OAUTHLIB_INSECURE_TRANSPORT"] = "1"
api_service_name = "youtube"
api_version = "v3"
client_secrets_file = "client_secret.json"
# Get credentials and create an API client
scopes = ["https://www.googleapis.com/auth/youtube.readonly"]
flow = google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file(
client_secrets_file, scopes)
credentials = flow.run_console()
# from the Youtube DATA API
youtube_client = googleapiclient.discovery.build(
api_service_name, api_version, credentials=credentials)
return youtube_client
def get_liked_videos(self):
"""Grab Our Liked Videos & Create A Dictionary Of Important Song Information"""
request = self.youtube_client.videos().list(
part="snippet,contentDetails,statistics",
myRating="like"
)
response = request.execute()
# collect each video and get important information
for item in response["items"]:
video_title = item["snippet"]["title"]
youtube_url = "https://www.youtube.com/watch?v={}".format(
item["id"])
# use youtube_dl to collect the song name & artist name
video = youtube_dl.YoutubeDL({}).extract_info(
youtube_url, download=False)
song_name = video["track"]
artist = video["artist"]
if song_name is not None and artist is not None:
# save all important info and skip any missing song and artist
self.all_song_info[video_title] = {
"youtube_url": youtube_url,
"song_name": song_name,
"artist": artist,
# add the uri, easy to get song to put into playlist
"spotify_uri": self.get_spotify_uri(song_name, artist)
}
def create_playlist(self):
"""Create A New Playlist"""
request_body = json.dumps({
"name": "Youtube Liked Vids",
"description": "All Liked Youtube Videos",
"public": True
})
query = "https://api.spotify.com/v1/users/{}/playlists".format(
spotify_user_id)
response = requests.post(
query,
data=request_body,
headers={
"Content-Type": "application/json",
"Authorization": "Bearer {}".format(spotify_token)
}
)
response_json = response.json()
# playlist id
return response_json["id"]
def get_spotify_uri(self, song_name, artist):
"""Search For the Song"""
query = "https://api.spotify.com/v1/search?query=track%3A{}+artist%3A{}&type=track&offset=0&limit=20".format(
song_name,
artist
)
response = requests.get(
query,
headers={
"Content-Type": "application/json",
"Authorization": "Bearer {}".format(spotify_token)
}
)
response_json = response.json()
songs = response_json["tracks"]["items"]
# only use the first song
uri = songs[0]["uri"]
return uri
def add_song_to_playlist(self):
"""Add all liked songs into a new Spotify playlist"""
# populate dictionary with our liked songs
self.get_liked_videos()
# collect all of uri
uris = [info["spotify_uri"]
for song, info in self.all_song_info.items()]
# create a new playlist
playlist_id = self.create_playlist()
# add all songs into new playlist
request_data = json.dumps(uris)
query = "https://api.spotify.com/v1/playlists/{}/tracks".format(
playlist_id)
response = requests.post(
query,
data=request_data,
headers={
"Content-Type": "application/json",
"Authorization": "Bearer {}".format(spotify_token)
}
)
# check for valid response status
if response.status_code != 200:
raise ResponseException(response.status_code)
response_json = response.json()
return response_json
if __name__ == '__main__':
cp = CreatePlaylist()
cp.add_song_to_playlist()
在终端中运行时:
192:SpotifyGeneratePlaylist-master paulkasidit$ python3 create_playlist.py
Please visit this URL to authorize this application: https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=550010103020-vdhbp618n05m8bf1sheerj0hsq0he3c4.apps.googleusercontent.com&redirect_uri=urn%3Aietf%3Awg%3Aoauth%3A2.0%3Aoob&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fyoutube.readonly&state=M1EQTEk5OW8RZxFmQknGvDZzdPgVlc&prompt=consent&access_type=offline
Enter the authorization code: 4/3gGLoigOQk85ZIFwEb-vhhVQ1czAaJmNZUSTRLoL-s5gEv0FNb-Q3Kk
[youtube] RiEXuE1uN0E: Downloading webpage
[youtube] wQuo7DhJ5dg: Downloading webpage
[youtube] wQuo7DhJ5dg: Downloading MPD manifest
[youtube] I7tehcZja_4: Downloading webpage
[youtube] 2MpZO7_u-oM: Downloading webpage
[youtube] aYjHOf6-SmM: Downloading webpage
Traceback (most recent call last):
File "create_playlist.py", line 154, in <module>
cp.add_song_to_playlist()
File "create_playlist.py", line 146, in add_song_to_playlist
raise ResponseException(response.status_code)
**exceptions.ResponseException: Response gave status code 400**
源项目链接:https://github.com/TheComeUpCode/SpotifyGeneratePlaylist
与Google合作时,其他人是否遇到过此问题 API 或YouTube API?有解决办法吗?
我的YouTube喜欢的视频中有3000多个视频,可能是
错误的原因? (我尝试使用仅
3个喜欢的视频,但是仍然会发生此错误。)
谢谢
*很抱歉重新发布此问题。我是一个完整的初学者,我不太擅长问好问题。我希望所提供的细节足够。