Nagraj93
Nagraj93

Reputation: 403

How does authentication in python work?

I am trying to work on musixmatch api. To get the json data I need to authenticate first,I have api key but i am unable to authenticate. I would like to know how to authenticate using urllib2 Thanks:

Ps:I tried doing this:

def download_file(url, API_KEY_BASE_64):
    req = urllib2.Request(url)
    req.add_header("Authorization", "Basic "+API_KEY_BASE_64)
    return urllib2.urlopen(req).read()

here

url="http://api.musixmatch.com/ws/1.1/track.lyrics.get?track_id=15953433"
api_key="MYAPIKEY"

response i got is:

{"message":{"header":{"status_code":401,"execute_time":0.0019550323486328,"maintenance_id":0},"body":""}}

Upvotes: 1

Views: 695

Answers (1)

Joaquin Sargiotto
Joaquin Sargiotto

Reputation: 1746

This isn't a problem with the authentication in python, but a problem with the way the api is expecting your api key.

This page: https://developer.musixmatch.com/documentation/input-parameters states that you must always send your api key as a parameter, so this code does exactly that:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import urllib2

api_key="XXXXXXXXXXXXXXXXXXXXXXXXXXXX"
# Note how I'm adding the api key as a parameter of the request url
url="http://api.musixmatch.com/ws/1.1/track.lyrics.get?track_id=15953433&apikey={}".format(api_key)

req = urllib2.Request(url)
req.add_header("Accept", "application/json")
response = urllib2.urlopen(req).read()
print response

PS: You could also use this library (https://github.com/monkeython/musixmatch), it wraps around the api and it seems easy to use.

Upvotes: 1

Related Questions