spotifyatlas


Namespotifyatlas JSON
Version 1.0.0 PyPI version JSON
download
home_page
SummaryA pythonic wrapper for the Spotify web API.
upload_time2023-01-24 06:03:31
maintainer
docs_urlNone
author
requires_python>=3.7
licenseCopyright (c) 2023 Leonardo Corona Garza Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
keywords spotify api wrapper web requests
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # spotifyatlas

### A pythonic wrapper for the Spotify web API.

By Leonardo - UmActually

`spotifyatlas` is a straightforward library meant to simplify the process of interacting with **Spotify's web API**. Whether you are trying to programmatically access Spotify features like **search queries**, or automate user tasks like **modifying your playlists**, spotifyatlas has tools for the job. All in a clean, object-oriented style.

Most of the package's functionality is included in the ``SpotifyAPI`` class, which only needs to be initialized with the **credentials** of your client application. This codebase was originally used to retrieve track details for **[Discord bots](https://github.com/UmActually/Papanatas)**, so most of the functions, as of now, revolve around playlists, albums, top tracks of artists, and whatnot.

## Basic Usage

_Refer to the [Installation](#installation) section for information on how to install the package with `pip`._

The first step to interact with the Spotify API is to register a new **application** in the **[Spotify for Developers](https://developer.spotify.com/dashboard/)** page. Worry not: this process is completely free for any Spotify user (with an account).

### Quick Start

With that out of the way, go ahead and initialize a new `SpotifyAPI` object with the credentials of your app (client ID and client secret):

```python
from spotifyatlas import SpotifyAPI
spoti = SpotifyAPI('<my-client-id>', '<my-client-secret>')
```

If you wish to retrieve the **tracks and/or details** of anything in Spotify, the universal `get()` method many times will get you covered.

Try it by pasting the share link of your favorite playlist. It will return a `Playlist` object. the playlist tracks are located in the `tracks` attribute, and you can also access tracks **by index**, as shown below.

```python
from spotifyatlas import SpotifyAPI
spoti = SpotifyAPI('<my-client-id>', '<my-client-secret>')
playlist = spoti.get('https://open.spotify.com/playlist/6xTnvRqIKptVfgcT8gN4Bb')

print(playlist.tracks)
# [<Track name='Goliath' artist='The Mars Volta' id='3bi3Ycf0ZlRHvSg0IxlMwM'>, ... ]

first_track = playlist[0]  # the same as playlist.tracks[0]  
print(first_track)
# Goliath - The Mars Volta
```

A `Track` contains the `name`, `artist`, `album` and `id` of a song. And, as you saw above, `print(track)` will format a track as `'<name> - <artist>'`. You can neatly list the contents of your playlist like this:

```python
for i, track in enumerate(playlist, 1):
    print(i, '-', track)
# 1 - Goliath - The Mars Volta
# 2 - Juicy - 2005 Remaster - The Notorious B.I.G.
# 3 - O Peso da Cruz - Supercombo
# 4 - Count The People (feat. Jessie Reyez & T-Pain) - Jacob Collier
# 5 - Touch - Shura
# ...
```

Similar to `Playlist` and `Track`, you can also find `Album`, `Artist` and `User` structures. *Every one of these is connected to each other* by **attributes**. For example, `track.artist.image_url` will return the image url of the artist of a track, and so will `track.album.tracks[0].artist.image_url`. I confidently assume you won't do it the second way. The increased amount of API requests will take its toll on performance.

### Getting

The following methods offer the same functionality as `get()`, although with a *specific return value*:

- `get_playlist()` for public playlists.

- `get_track()` for tracks.

- `get_artist()` for artists and their top 10 tracks.

- `get_album()` for albums.

- `get_user()` for users.

They all require the `url` or the ID of the element as the first argument.

### Searching

Not everything demands you having the link of the item at hand. To perform **searches**, you can use the following methods:

- `search()` to search normally, with the option to specify result types.

```python
result = spoti.search('susanne sundfor')
top_artist_result = result.artists[0]
print(top_artist_result.name)
# Susanne Sundfør

result = spoti.search('ok human')
top_album_result = result.albums[0]
print(top_album_result.tracks)
# [<Track name='All My Favorite Songs' artist='Weezer' id='6zVhXpiYbJhLJWmLGV9k1r'>, ... ]
```

- `im_feeling_lucky()` if you know in advance exactly what you are looking for. It is essentially the same as `search()` but returns directly the top result of the specified type.

```python
from spotifyatlas import ResultType
result = spoti.im_feeling_lucky('quevedo biza', ResultType.TRACK)
print(result)
# Quevedo: Bzrp Music Sessions, Vol. 52 - Bizarrap
```

- The standalone function `spotifyatlas.advanced_search()` can generate a more [powerful search query](https://support.spotify.com/us/article/search/) that the user can then pass to either of the search methods (or even paste to their actual Spotify client).

```python
from spotifyatlas import ResultType, Genre, advanced_search

overkill_query = advanced_search(
    'juanes',
    album='metallica',
    year=2021,
    genre=Genre.ROCK
)

result = spoti.im_feeling_lucky(overkill_query, ResultType.TRACK)
print(result)
# Enter Sandman - Juanes
```

### User Functionality

These other methods require **user consent**, and thus will result in the **browser** opening for the authorization of your application to act on behalf of the user:

- `get_me()` for details of your own profile.

- `get_private_playlist()` for private playlists you own.

- `create_playlist()` to make a new empty playlist in your library.

- `add_to_playlist()` to add a batch of `Track`s to a playlist.

- `duplicate_playlist()` to duplicate a playlist in your library.

- `clear_playlist()` to remove all the contents of a playlist.

- `rearrange_playlist()` to change the position of a range of tracks.

The last five functions are also available as **methods** of the `Playlist` class. This enables some handy shortcuts like the ones seen in [More Examples](#more-examples).

> Note: authorizing the application in the Spotify authorization page requires a **redirection** page to go to. This library will temporarily **host a local page** on http://localhost:8000 whenever needed. Thus, you **will need to add this URL** to the allowed redirection URLs on the dashboard of your application in the **[Spotify for Developers](https://developer.spotify.com/dashboard/)** site.

The complete list of parameters/arguments of a function can be found in its documentation.

---

## Installation

To install spotifyatlas, use **pip** in the terminal:

**Windows**
```commandline
pip install spotifyatlas
```

**macOS / Linux**
```commandline
python3 -m pip install spotifyatlas
```

---

## More Examples

For the inquisitive user, here are some more code examples out the top of my head:

### 1. Rearrange the tracks of a playlist by artist, alphabetically

```python
from spotifyatlas import SpotifyAPI


def artist_sort_key(track):  
    return track.artist.name.lower()  
    # If you want to hierarchically sort by artist, AND album,  
    # AND track, use this:
    # return (
    #     track.artist.name.lower(),
    #     track.album.name.lower(),
    #     track.name.lower())


MY_PLAYLIST = '<my-playlist-link>'
spoti = SpotifyAPI('<my-client-id>', '<my-client-secret>')

playlist = spoti.get_playlist(MY_PLAYLIST)  
tracks = playlist.tracks  
tracks.sort(key=artist_sort_key)  
  
# make_copy makes a backup of the playlist in your library  
# before removing its contents.  
playlist.clear(make_copy=True)  
playlist.add(tracks)
```

### 2. Find the songs that two playlists have in common, and create a playlist with them

```python
from spotifyatlas import SpotifyAPI

MY_PLAYLIST = '<my-playlist-link>'
MY_FRIENDS_PLAYLIST = '<my-friends-playlist-link>'

spoti = SpotifyAPI('<my-client-id>', '<my-client-secret>')

playlist1 = spoti.get(MY_PLAYLIST)
playlist2 = spoti.get(MY_FRIENDS_PLAYLIST)

# Set theory!!!  
common_tracks = set(playlist1).intersection(set(playlist2))  
for i, track in enumerate(common_tracks, 1):  
    print(i, '-', track)  
  
blend = spoti.create_playlist(  
    name=f'{playlist1.owner.name} + {playlist2.owner.name}',  
    description='I am a blend, I swear')  

blend.add(list(common_tracks))
```

---

## Who Is This Package For

I've created `spotifyatlas` to encourage music lovers and programmers alike, to draw on the elegance of Python automation and **scripting**. If you stumbled upon this package while looking for a way to **extend the user capabilities** in Spotify beyond the user interface, then you are in the right place.

If instead you are looking for an API wrapper for use in a Python **web application**, maybe this package is not the right choice. For starters, the library's functionality is **not asynchronous** (not yet, at least). Perhaps this is okay for a couple of simple tasks, though. And also, as of now, the way I implemented authorization flow is not compatible with a web app (it literally opens a localhost page). This means it would only work with functions that do not require user auth.

            

Raw data

            {
    "_id": null,
    "home_page": "",
    "name": "spotifyatlas",
    "maintainer": "",
    "docs_url": null,
    "requires_python": ">=3.7",
    "maintainer_email": "",
    "keywords": "spotify,api,wrapper,web,requests",
    "author": "",
    "author_email": "Leonardo Corona Garza <leocoronag@gmail.com>",
    "download_url": "https://files.pythonhosted.org/packages/ee/a4/941524914857645f433054aed88f62de96e827fd2470460f703ab0f4b459/spotifyatlas-1.0.0.tar.gz",
    "platform": null,
    "description": "# spotifyatlas\n\n### A pythonic wrapper for the Spotify web API.\n\nBy Leonardo - UmActually\n\n`spotifyatlas` is a straightforward library meant to simplify the process of interacting with **Spotify's web API**. Whether you are trying to programmatically access Spotify features like **search queries**, or automate user tasks like **modifying your playlists**, spotifyatlas has tools for the job. All in a clean, object-oriented style.\n\nMost of the package's functionality is included in the ``SpotifyAPI`` class, which only needs to be initialized with the **credentials** of your client application. This codebase was originally used to retrieve track details for **[Discord bots](https://github.com/UmActually/Papanatas)**, so most of the functions, as of now, revolve around playlists, albums, top tracks of artists, and whatnot.\n\n## Basic Usage\n\n_Refer to the [Installation](#installation) section for information on how to install the package with `pip`._\n\nThe first step to interact with the Spotify API is to register a new **application** in the **[Spotify for Developers](https://developer.spotify.com/dashboard/)** page. Worry not: this process is completely free for any Spotify user (with an account).\n\n### Quick Start\n\nWith that out of the way, go ahead and initialize a new `SpotifyAPI` object with the credentials of your app (client ID and client secret):\n\n```python\nfrom spotifyatlas import SpotifyAPI\nspoti = SpotifyAPI('<my-client-id>', '<my-client-secret>')\n```\n\nIf you wish to retrieve the **tracks and/or details** of anything in Spotify, the universal `get()` method many times will get you covered.\n\nTry it by pasting the share link of your favorite playlist. It will return a `Playlist` object. the playlist tracks are located in the `tracks` attribute, and you can also access tracks **by index**, as shown below.\n\n```python\nfrom spotifyatlas import SpotifyAPI\nspoti = SpotifyAPI('<my-client-id>', '<my-client-secret>')\nplaylist = spoti.get('https://open.spotify.com/playlist/6xTnvRqIKptVfgcT8gN4Bb')\n\nprint(playlist.tracks)\n# [<Track name='Goliath' artist='The Mars Volta' id='3bi3Ycf0ZlRHvSg0IxlMwM'>, ... ]\n\nfirst_track = playlist[0]  # the same as playlist.tracks[0]  \nprint(first_track)\n# Goliath - The Mars Volta\n```\n\nA `Track` contains the `name`, `artist`, `album` and `id` of a song. And, as you saw above, `print(track)` will format a track as `'<name> - <artist>'`. You can neatly list the contents of your playlist like this:\n\n```python\nfor i, track in enumerate(playlist, 1):\n    print(i, '-', track)\n# 1 - Goliath - The Mars Volta\n# 2 - Juicy - 2005 Remaster - The Notorious B.I.G.\n# 3 - O Peso da Cruz - Supercombo\n# 4 - Count The People (feat. Jessie Reyez & T-Pain) - Jacob Collier\n# 5 - Touch - Shura\n# ...\n```\n\nSimilar to `Playlist` and `Track`, you can also find `Album`, `Artist` and `User` structures. *Every one of these is connected to each other* by **attributes**. For example, `track.artist.image_url` will return the image url of the artist of a track, and so will `track.album.tracks[0].artist.image_url`. I confidently assume you won't do it the second way. The increased amount of API requests will take its toll on performance.\n\n### Getting\n\nThe following methods offer the same functionality as `get()`, although with a *specific return value*:\n\n- `get_playlist()` for public playlists.\n\n- `get_track()` for tracks.\n\n- `get_artist()` for artists and their top 10 tracks.\n\n- `get_album()` for albums.\n\n- `get_user()` for users.\n\nThey all require the `url` or the ID of the element as the first argument.\n\n### Searching\n\nNot everything demands you having the link of the item at hand. To perform **searches**, you can use the following methods:\n\n- `search()` to search normally, with the option to specify result types.\n\n```python\nresult = spoti.search('susanne sundfor')\ntop_artist_result = result.artists[0]\nprint(top_artist_result.name)\n# Susanne Sundf\u00f8r\n\nresult = spoti.search('ok human')\ntop_album_result = result.albums[0]\nprint(top_album_result.tracks)\n# [<Track name='All My Favorite Songs' artist='Weezer' id='6zVhXpiYbJhLJWmLGV9k1r'>, ... ]\n```\n\n- `im_feeling_lucky()` if you know in advance exactly what you are looking for. It is essentially the same as `search()` but returns directly the top result of the specified type.\n\n```python\nfrom spotifyatlas import ResultType\nresult = spoti.im_feeling_lucky('quevedo biza', ResultType.TRACK)\nprint(result)\n# Quevedo: Bzrp Music Sessions, Vol. 52 - Bizarrap\n```\n\n- The standalone function `spotifyatlas.advanced_search()` can generate a more [powerful search query](https://support.spotify.com/us/article/search/) that the user can then pass to either of the search methods (or even paste to their actual Spotify client).\n\n```python\nfrom spotifyatlas import ResultType, Genre, advanced_search\n\noverkill_query = advanced_search(\n    'juanes',\n    album='metallica',\n    year=2021,\n    genre=Genre.ROCK\n)\n\nresult = spoti.im_feeling_lucky(overkill_query, ResultType.TRACK)\nprint(result)\n# Enter Sandman - Juanes\n```\n\n### User Functionality\n\nThese other methods require **user consent**, and thus will result in the **browser** opening for the authorization of your application to act on behalf of the user:\n\n- `get_me()` for details of your own profile.\n\n- `get_private_playlist()` for private playlists you own.\n\n- `create_playlist()` to make a new empty playlist in your library.\n\n- `add_to_playlist()` to add a batch of `Track`s to a playlist.\n\n- `duplicate_playlist()` to duplicate a playlist in your library.\n\n- `clear_playlist()` to remove all the contents of a playlist.\n\n- `rearrange_playlist()` to change the position of a range of tracks.\n\nThe last five functions are also available as **methods** of the `Playlist` class. This enables some handy shortcuts like the ones seen in [More Examples](#more-examples).\n\n> Note: authorizing the application in the Spotify authorization page requires a **redirection** page to go to. This library will temporarily **host a local page** on http://localhost:8000 whenever needed. Thus, you **will need to add this URL** to the allowed redirection URLs on the dashboard of your application in the **[Spotify for Developers](https://developer.spotify.com/dashboard/)** site.\n\nThe complete list of parameters/arguments of a function can be found in its documentation.\n\n---\n\n## Installation\n\nTo install spotifyatlas, use **pip** in the terminal:\n\n**Windows**\n```commandline\npip install spotifyatlas\n```\n\n**macOS / Linux**\n```commandline\npython3 -m pip install spotifyatlas\n```\n\n---\n\n## More Examples\n\nFor the inquisitive user, here are some more code examples out the top of my head:\n\n### 1. Rearrange the tracks of a playlist by artist, alphabetically\n\n```python\nfrom spotifyatlas import SpotifyAPI\n\n\ndef artist_sort_key(track):  \n    return track.artist.name.lower()  \n    # If you want to hierarchically sort by artist, AND album,  \n    # AND track, use this:\n    # return (\n    #     track.artist.name.lower(),\n    #     track.album.name.lower(),\n    #     track.name.lower())\n\n\nMY_PLAYLIST = '<my-playlist-link>'\nspoti = SpotifyAPI('<my-client-id>', '<my-client-secret>')\n\nplaylist = spoti.get_playlist(MY_PLAYLIST)  \ntracks = playlist.tracks  \ntracks.sort(key=artist_sort_key)  \n  \n# make_copy makes a backup of the playlist in your library  \n# before removing its contents.  \nplaylist.clear(make_copy=True)  \nplaylist.add(tracks)\n```\n\n### 2. Find the songs that two playlists have in common, and create a playlist with them\n\n```python\nfrom spotifyatlas import SpotifyAPI\n\nMY_PLAYLIST = '<my-playlist-link>'\nMY_FRIENDS_PLAYLIST = '<my-friends-playlist-link>'\n\nspoti = SpotifyAPI('<my-client-id>', '<my-client-secret>')\n\nplaylist1 = spoti.get(MY_PLAYLIST)\nplaylist2 = spoti.get(MY_FRIENDS_PLAYLIST)\n\n# Set theory!!!  \ncommon_tracks = set(playlist1).intersection(set(playlist2))  \nfor i, track in enumerate(common_tracks, 1):  \n    print(i, '-', track)  \n  \nblend = spoti.create_playlist(  \n    name=f'{playlist1.owner.name} + {playlist2.owner.name}',  \n    description='I am a blend, I swear')  \n\nblend.add(list(common_tracks))\n```\n\n---\n\n## Who Is This Package For\n\nI've created `spotifyatlas` to encourage music lovers and programmers alike, to draw on the elegance of Python automation and **scripting**. If you stumbled upon this package while looking for a way to **extend the user capabilities** in Spotify beyond the user interface, then you are in the right place.\n\nIf instead you are looking for an API wrapper for use in a Python **web application**, maybe this package is not the right choice. For starters, the library's functionality is **not asynchronous** (not yet, at least). Perhaps this is okay for a couple of simple tasks, though. And also, as of now, the way I implemented authorization flow is not compatible with a web app (it literally opens a localhost page). This means it would only work with functions that do not require user auth.\n",
    "bugtrack_url": null,
    "license": "Copyright (c) 2023 Leonardo Corona Garza  Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:  The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.  THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ",
    "summary": "A pythonic wrapper for the Spotify web API.",
    "version": "1.0.0",
    "split_keywords": [
        "spotify",
        "api",
        "wrapper",
        "web",
        "requests"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "e4e4187f1aca8b0cfabc323540b743adcf3b9d46b972673da52e27e5d5862507",
                "md5": "24b6d6db08fb8b97a3c70b14b4f4aee7",
                "sha256": "4023443f1beb0cef4592b1c6fc0755e64d09568dd7635a3a02a682a1df6205f7"
            },
            "downloads": -1,
            "filename": "spotifyatlas-1.0.0-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "24b6d6db08fb8b97a3c70b14b4f4aee7",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.7",
            "size": 25145,
            "upload_time": "2023-01-24T06:03:25",
            "upload_time_iso_8601": "2023-01-24T06:03:25.850265Z",
            "url": "https://files.pythonhosted.org/packages/e4/e4/187f1aca8b0cfabc323540b743adcf3b9d46b972673da52e27e5d5862507/spotifyatlas-1.0.0-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "eea4941524914857645f433054aed88f62de96e827fd2470460f703ab0f4b459",
                "md5": "81779434bbf5ccd5f7c240dc652cdfa9",
                "sha256": "e5db4dcc7e2f4a65b63fb84fef33ea3544480e43cc62d4fbad79875c0d81368f"
            },
            "downloads": -1,
            "filename": "spotifyatlas-1.0.0.tar.gz",
            "has_sig": false,
            "md5_digest": "81779434bbf5ccd5f7c240dc652cdfa9",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.7",
            "size": 25897,
            "upload_time": "2023-01-24T06:03:31",
            "upload_time_iso_8601": "2023-01-24T06:03:31.163459Z",
            "url": "https://files.pythonhosted.org/packages/ee/a4/941524914857645f433054aed88f62de96e827fd2470460f703ab0f4b459/spotifyatlas-1.0.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2023-01-24 06:03:31",
    "github": false,
    "gitlab": false,
    "bitbucket": false,
    "lcname": "spotifyatlas"
}
        
Elapsed time: 0.03147s