Search code examples
javascriptpythonapigetspotify

Why are dots in track name confusing searches via Spotify Web API?


For example, we want to search for a track Sixx:A.M. Life Is Beautiful. To do it, go to Spotify Console. The total int the response is zero. Nothing found.

Now, go to the site. Paste the same text Sixx:A.M. Life Is Beautiful into the search field. The result is more than one.

What's the problem?

Description search request

Response:

{
  "tracks": {
    "href": "https://api.spotify.com/v1/search?query=Sixx%3AA.M.+Life+Is+Beautiful&type=track&offset=0&limit=1",
    "items": [],
    "limit": 1,
    "next": null,
    "offset": 0,
    "previous": null,
    "total": 0
  }
}

Site url:

https://open.spotify.com/search/Sixx%3AA.M.%20Life%20Is%20Beautiful

UPDATE

If dots are removed from the string - Sixx:AM Life Is Beautiful - Spotify Console returns the needed track! But for example P.O.D. Find My Way - dots do not interfere, the result is given with them. I don't understand how it works...


Solution

  • Because the query parameter is not a simple "search string", like the website. Is a string that has fields and operators, as you can read in the documentation. Passing the user input directly as a query parameter can lead to problems, as the user can write a filter o an operator without knowing it. You should either:

    • Notify the user about this. The user will write operators and such knowing what he is doing.
    • Parse the string received and create a proper query parameter.

    I guess that Spotify don't like weird characters in their query, as dots and such (the same as Google for example, but Google filter them), so I recommend to just parse the string, remove dots, convert all non alphanumeric characters to spaces and make all the string lower case so there are no operators (as documentation says that operators are upper case). So:

    function cleanQuery(str) {
      return encodeURIComponent(str.replace(/\./g, "").replace(/[^0-9a-z]/gi, " ").toLowerCase());
    }
    
    console.log("Clean \"Sixx:A.M. Life Is Beautiful\":", cleanQuery("Sixx:A.M. Life Is Beautiful"));

    I've made a query with the returned result and it worked:enter image description here

    Note that this is a fast test. I noticed that the problem with dots is that they are not the first word. Maybe there are more characters with problems, as dashes, for example. This is going to be a trial-and-error thingy, as the documentation is kinda vague (not documenting dots, for example).