:snake: A simple library to fetch data from the iTunes Store API made for Python >= 3.5

Overview

itunespy PyPI version

itunespy is a simple library to fetch data from the iTunes Store API made for Python 3.5 and beyond.

Important: Since version 1.6 itunespy no longer supports versions below Python 3.5. You can still use any previous versions but those won't get any further updates or features.

Installing

You can install it from pip:

pip install itunespy

Or you can simply clone this project anywhere in your computer:

git clone https://github.com/sleepyfran/itunespy.git

And then enter the cloned repo and execute:

python setup.py install

Dependencies

itunespy requires Requests and pycountry installed.

Examples and information

Search an artist and show all its album's names:

import itunespy

artist = itunespy.search_artist('Steven Wilson')  # Returns a list
albums = artist[0].get_albums()  # Get albums from the first result

for album in albums:
    print(album.collection_name)

Or search an album and show all its song's names and length, and finally the album length:

import itunespy

album = itunespy.search_album('One Hour By The Concrete Lake')  # Returns a list
tracks = album[0].get_tracks()  # Get tracks from the first result

for track in tracks:
    print(track.artist_name + ': ' + track.track_name + str(track.get_track_time_minutes()))
print('Total playing time: ' + str(album[0].get_album_time()))

Or search for a track:

import itunespy

track = itunespy.search_track('Iter Impius')  # Returns a list
print(track[0].artist_name + ': ' + track[0].track_name + ' | Length: ' + str(track[0].get_track_time_minutes())) # Get info from the first result

Or ebook authors:

import itunespy

author = itunespy.search_book_author('Fyodor Dostoevsky')  # Search for Dostoevsky

books = author[0].get_books()  # Get books from the firs result

for book in books:
    print(book.track_name)  # Show each book's name

Or software:

import itunespy

telegram = itunespy.search_software('Telegram')

print(telegram[0].track_name)  # Prints 'Telegram Messenger'

Basically, every search_ method is just an alias for a general search with certain parameters to make your life easier.

I made the basic ones, if you miss any, make an issue and provide information about the type you want added.

You can also perform a lookup:

import itunespy

lookup = itunespy.lookup(upc=720642462928) # Lookup for the Weezer's album 'Weezer'

for item in lookup:
    print(item.artist_name + ': ' + item.collection_name)

Since every search or lookup can return more than one object type, every object in the returned list has a 'type' property, so you can check if it's an artist, album or track like this:

import itunespy

lookup = itunespy.lookup(id=428011728)  # Steven Wilson's ID

for l in lookup:
    if l.type == 'artist':
        print('Artist!')
        print(l.artist_type)  # Since it's an artist, you can also check its artist type

For a complete list, take a look at the wrapperType and kind documentation in the iTunes API's site.

Each request has some parameters that you need to know. Searches has these:

term: The URL-encoded text string you want to search for. Example: Steven Wilson.
        The function will take care of spaces so you don't have to.
country: The two-letter country code for the store you want to search.
        For a full list of the codes: http://en.wikipedia.org/wiki/%20ISO_3166-1_alpha-2
media: The media type you want to search for. Since this module is made for music I recommend leaving it blank.
entity: The type of results you want returned, relative to the specified media type. Example: musicArtist.
        Full list: musicArtist, musicTrack, album, musicVideo, mix, song
attribute: The attribute you want to search for in the stores, relative to the specified media type.
limit: The number of search results you want the iTunes Store to return.

Note: Only the term is obligatory, the other ones have default values that will be used in case you don't provide any. Note 2: In specific searches, like search_artist or search_album, etc, don't change entity, since it's configured inside the function to retrieve an specific entity.

For lookups, the same parameters apply except for term, which changes to a couple of id fields:

id: iTunes ID of the artist/album/track
artist_amg_id: All Music Guide ID of the artist
upc: UPCs/EANs

Every search and lookup will always return a list of result_item instances, except if it's an artist, album, movie artist or an ebook author, which inheritates from result_item but has extra methods, like get_albums in music_artist. Each object has their own variables, following the iTunes API names adapted to Python syntax.

To take a look at all of this simply go to the item_result class.

Contributing

I'm accepting any pull request to improve or fix anything in the library, just fork the project and hack it!

Comments
  • [Feature Request] Add a setter method for track_time

    [Feature Request] Add a setter method for track_time

    Hey there, thanks for the nice project!

    I am the developer of ytmdl and my project has been dependent on your library since the beginning.

    It was later that I noticed that the track_time property of the songs are returned in miliseconds, however, my requirement was to get them in seconds, so I added a bit of code that updates the track_time value and then passed the whole results container along.

    It was working all nice and well until the last release. You made the move to change track_time to a property and it turns out the property doesn't have a setter method which is why my code was unable to update the track_time value and so as a result a lot of users started facing the issue.

    However, a few days ago a fellow user pointed out the issue to me and I found out about the latest release that broke my code.

    I just wanted to request to please add a setter method for the track_time property so that I can go back to using all the latest releases as currently I have forced the version 1.5.5 in the setup.

    Cheers! Thanks for the awesome library, really appreciate it.

    enhancement 
    opened by deepjyoti30 5
  • Possible to to download movies ?

    Possible to to download movies ?

    is it possible to download movies that i bought with python and sync it with the library ? iTunes produce horrible speeds ..i tried with IDM but that don't work bcs i can't play the file maybe library sync issue .

    question 
    opened by dualriposte 3
  • Add country support for sub-queries

    Add country support for sub-queries

    When searching the iTunes API it is possible to specify a country. This way one might get a MusicAlgum from the _get_result_list method. Using the get_tracks method on such an album will lookup the album. This however does not retain the country that was initially specified. For albums that are not available on the default (US) iTunes Store this causes get_tracks to effectively fail (no results are returned).

    This pull request adds the country field to ResultItem and retains the country from a search or lookup operation in the respective results. It also modifies the get_tracks method to lookup tracks in the same country that the MusicAlbum belongs to.

    opened by codello 2
  • Way to search by ISRC?

    Way to search by ISRC?

    I'm using the Spotify and iTunes API together and need a way to guarantee the results returned from each are the same. I haven't found a way to search by ISRC with your wrapper but maybe I missed something.

    question 
    opened by kylesurowiec 2
  • taking song that not matches the given id

    taking song that not matches the given id

    This is the code I used to search the specific song. I couldn't figure out where the error would be in the itunespy code .

    import itunespy
    
    
    def main():
        #working song
        #broken arrows avici https://music.apple.com/us/album/stories/1440834059
        #id_number = '1440834528'
    
        #tragic the kid laroy https://music.apple.com/gb/album/tragic-feat-youngboy-never-broke-again-internet-money/1538646756?i=1538647031
        id_number = '1538647031'
        #actiall id itunespy looks up 341728831
    
        track_info = itunespy.lookup(id=id_number)
        album_info = itunespy.lookup(id=track_info[0].collectionId)
    
        track = itunespy.search_track('arrows')
        print(track[0].artist_name + ': ' + track[0].track_name + ' | Length: ' + str(
            track[0].get_track_time_minutes()))  # Get info from the first result
    
    if __name__ == '__main__':
        main()
    
    opened by JensDeLeersnyderPXL 1
  • Asynchronous version

    Asynchronous version

    Hi would it be possible to make an async version with aiohttp? I would modify it myself but I'm fairly new to python so if it's something you're willing to do I'd be grateful. Otherwise if you could point me in the right direction that'd be good too.

    opened by describe19 1
  • Type hints and more

    Type hints and more

    This pull request includes a number of things:

    • Type annotations for every function
    • URL escaping via urllib.parse. This has the following implications:
      • Simpler Code
      • Fixes a bug where if only the artist_amg_id or only the ups was specified for a lookup operation the function would raise an error.
      • Fixes a bug where special characters in search term or other query parameters would not be properly escaped.
    • Dynamic property access in ResultItem this makes it easier to support any new attributes added to the iTunes Search API. Known attributes are included as type hints to help type checkers and IDEs.
    • A new Artist class that is made the superclass of all artist types. The main purpose of this is to provide a more intuitive way to type hint any artist (which is needed search_director for example).
    • The __repr__ function now returns the underlying JSON object of a ResultItem.
    • A Github Actions Workflow that checks the consistency of type annotations via MyPy.
    • Drop support for Python 3.4

    I did try to make all of the changes backwards compatible. The following functions may behave slightly differently:

    • Performing lookups and searches does not raise an error anymore if the artist_amg_id or ups is not a str (at least in some cases). I consider this a bugfix.
    • collection_type, artist_type and track_type are now available in a ResultItem even if it does not have a wrapperType. This is to provide a more consistent interface allowing to query arbitrary fields in a result.
    • The __repr__ function of ResultItems now returns a different value.
    opened by codello 1
  • Documentation Clarification

    Documentation Clarification

    hi in your code file, it states a string to be passed... but in your README.md you use an integer...

    Could you please clarify which value type?

    --------

    def lookup(id=None, artist_amg_id=None, upc=None, country='US', media='all', entity=None, attribute=None, limit=50): """ Returns the result of the lookup of the specified id, artist_amg_id or upc in an array of result_item(s) :param id: String. iTunes ID of the artist, album, track, ebook or software :param artist_amg_id: String. All Music Guide ID of the artist :param upc: String. UPCs/EANs :param country: String. The two-letter country code for the store you want to search. For a full list of the codes: http://en.wikipedia.org/wiki/%20ISO_3166-1_alpha-2 :param media: String. The media type you want to search for. Example: music :param entity: String. The type of results you want returned, relative to the specified media type. Example: musicArtist. Full list: musicArtist, musicTrack, album, musicVideo, mix, song :param attribute: String. The attribute you want to search for in the stores, relative to the specified media type. :param limit: Integer. The number of search results you want the iTunes Store to return. :return: An array of result_item(s) """

    question 
    opened by jasonkolodziej 1
Releases(1.6)
  • 1.6(May 13, 2020)

    Thanks to the wonderful @codello who did all the amazing work on this release! 👍


    • 🔥 Breaking: This version and further versions of itunespy will NOT support any Python version below 3.5. If you need to use this library in any other version you can use itunespy <= 1.5.5 but those won't get any support or new features.
    • 🔥 Breaking: __repr__ now returns a different value (see below) so make sure you don't use this in a non-compatible way before updating.

    • 😄 Type hints are now available throughout the code
    • 😄 collection_type, artist_type and track_type are now available in a ResultItem even if it does not have a wrapperType. This is to provide a more consistent interface allowing to query arbitrary fields in a result.
    • 😄 __repr__ now returns the underlying JSON object of a ResultItem.
    • 😄 ResultItem now has a get_country() method for converting between country code formats via pycountry.
    • 🐛 The country specified in a query is now preserved in any sub-query. Example: Specifying a country via search_artist will now retain that same country when doing a get_albums.
    • 🐛 Performing lookups and searches does not raise an error anymore if the artist_amg_id or ups is not a str.
    • 🐛 Fixed cases in which special characters in search terms or other query parameters would not be properly escaped.
    Source code(tar.gz)
    Source code(zip)
  • 1.5.5(Oct 7, 2015)

  • v1.5(Sep 2, 2015)

    • 😄 Now you can get a Track time in minutes and hours using get_track_time_minutes() and get_track_time_hours()
    • 😄 The function get_tracks() in MusicAlbum now stores all tracks in _track_list if it's empty
    • 😄 You can also get the full playing time of an album using get_album_time()
    • 😄 search_director and search_movie implemented
    Source code(tar.gz)
    Source code(zip)
  • v1.3(Aug 23, 2015)

    • 🔥 Breaking: This new release deprecates the use of artist_genre_name and artist_genre_id in favor of primary_genre_name and primary_genre_id since those properties can be in artists, albums, tracks and more.
    Source code(tar.gz)
    Source code(zip)
Owner
Fran González
Music, code, repeat.
Fran González
Build a better understanding of your data in PostgreSQL.

Data Fluent for PostgreSQL Build a better understanding of your data in PostgreSQL. The following shows an example report generated by this tool. It g

Mark Litwintschik 28 Aug 30, 2022
A Python wrapper for the DeepL API

deepl.py A Python wrapper for the DeepL API installing Install and update using pip: pip install deepl.py A simple example. # Sync Sample import deep

grarich 18 Dec 12, 2022
Hack WhatsApp Account Easily(Android)

X-Whatsapp Hack WhatsApp Account Easily(Android) HOW TO RUN 👇 (Termux) pkg update && pkg upgrade pkg install python pkg install git git clone https:/

KiLL3R_xRO 72 Dec 21, 2022
Python Discord Server Nuker

Untitled Nuker Python Discord Server Nuker Features: Ban Everyone Kick Everyone Rename Everyone Spam To All Channels Delete All Channels Delete All Ro

22 Dec 22, 2022
OpenQuake's Engine for Seismic Hazard and Risk Analysis

OpenQuake Engine The OpenQuake Engine is an open source application that allows users to compute seismic hazard and seismic risk of earthquakes on a g

Global Earthquake Model 281 Dec 21, 2022
Request based Python module(s) to help with the Newegg raffle.

Newegg Shuffle Python module(s) to help you with the Newegg raffle How to use $ git clone https://github.com/Matthew17-21/Newegg-Shuffle $ cd Newegg-S

Matthew 45 Dec 01, 2022
Discord bot code to stop users that are scamming with fake messages of free discord nitro on servers in order to steal users accounts.

AntiScam Discord bot code to stop users that are scamming with fake messages of free discord nitro on servers in order to steal users accounts. How to

H3cJP 94 Dec 15, 2022
AWS Lambda Fast API starter application

AWS Lambda Fast API Fast API starter application compatible with API Gateway and Lambda Function. How to deploy it? Terraform AWS Lambda API is a reus

OBytes 6 Apr 20, 2022
Microsoft Azure Storage Library for Python

Microsoft Azure Storage Library for Python

Microsoft Azure 329 Dec 16, 2022
This is an implementation example of a bot that periodically sends predictions to the alphasea-agent.

alphasea-example-model alphasea-example-modelは、 alphasea-agent に対して毎ラウンド、予測を投稿するプログラムです。 Numeraiのexample modelに相当します。 準備 alphasea-example-modelの動作には、

AlphaSea 11 Jul 28, 2022
Google Sheets Python API v4

pygsheets - Google Spreadsheets Python API v4 A simple, intuitive library for google sheets which gets your work done. Features: Open, create, delete

Nithin Murali 1.4k Jan 08, 2023
Search stock images (e.g. via Unsplash) and save them to your Wagtail image library.

Wagtail Stock Images Search stock images (e.g. via Unsplash) and save them to your Wagtail image library. Requirements Python 3 Django = 2 Wagtail =

Vicktor 12 Oct 12, 2022
Battle Pass farming tft bot

Tft bot Bot para farmar pontos do Passe de Batalha do TFT Descrição A cada partida de tft jogada você ganha 100 pontos no passe, porém você não precis

Leonardo Gonçalves 4 Jan 27, 2022
A simple Discord Bot created for basic functionality and fun chat commands for use in a private server.

LoveAndChaos-Bot v0.1.0 LoveAndChaos-Bot is a Discord Bot specifically designed for a private server; this bot is merely a test and a method to expose

Morgan Rose 1 Dec 12, 2021
Implementation of the paper 'Sentence Bottleneck Autoencoders from Transformer Language Models'

Introduction This repository contains the code for the paper Sentence Bottleneck Autoencoders from Transformer Language Models by Ivan Montero, Nikola

Ivan Montero 14 Dec 28, 2022
Save data from Instagram takeout to a SQLite database

instagram-to-sqlite Save data from a Instagram takeout to a SQLite database. Mise En Place git clone https://github.com/gavindsouza/instagram-to-sqlit

gavin 8 Dec 13, 2022
A discord Server Bot made with Python, This bot helps people feel better by inspiring them with motivational quotes or by responding with a great message, also the users of the server can create custom messages by telling the bot with Commands.

A discord Server Bot made with Python, This bot helps people feel better by inspiring them with motivational quotes or by responding with a great message, also the users of the server can create cust

Aran 1 Oct 13, 2021
A telegram to pyrogram json bot

Pyrogram-Json-Bot A telegram to pyrogram json bot Please fork this repository don't import code Made with Python3 (C) @FayasNoushad Copyright permissi

Fayas Noushad 11 Dec 20, 2022
veez music bot is a telegram music bot project, allow you to play music on voice chat group telegram.

🎶 VEEZ MUSIC BOT Veez Music is a telegram bot project that's allow you to play music on telegram voice chat group. Requirements 📝 FFmpeg NodeJS node

levina 143 Jun 19, 2022
A Discord token grabber executing in a Microsoft Document.

🦊 Rage 🦊 Rage is a tool written in Python3 allowing you to inject a Python3 complete Discord token grabber (Riot) script in a Microsoft Document usi

Billy 73 Nov 03, 2022