Abdul Rehman
Abdul Rehman

Reputation: 5644

Implement Github API in Python

I'm working on a project using Python(3.6) in which I need to implement GitHub API. I have tried by using JSON apis as:

from views.py:

class GhNavigator(CreateView):
    def get(self, request, *args, **kwargs):
        term = request.GET.get('search_term')
        username = 'arycloud'
        token = 'API_TOKEN'
        login = requests.get('https://api.github.com/search/repositories?q=' + term, auth=(username, token))
        print(login)
        return render(request, 'navigator/template.html', {'login': login})

but it simply returns status 200, I want to get a list of repositories for term which is passed by the user.

How can I achieve that?

Help me, please!

Thanks in advance!

Upvotes: 4

Views: 879

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476557

The requests library will return a Response object if you perform a .get(..), .post(..) or anything like that. Since responses can be very huge (hundreds of lines), it does not print the content by default.

But the developers attached some convenient functions to it, for example to interpet the answer as a JSON object. A response object has a .json() function that aims to interpret the content as a JSON string, and returns its Vanilla Python counterpart.

So you can access the response (and render it the way you want), by calling .json(..) on it:

class GhNavigator(CreateView):
    def get(self, request, *args, **kwargs):
        term = request.GET.get('search_term')
        username = 'arycloud'
        token = 'API_TOKEN'
        response = requests.get('https://api.github.com/search/repositories?q=' + term, auth=(username, token))
        login = response.json()  # obtain the payload as JSON object
        print(login)
        return render(request, 'navigator/template.html', {'login': login})

Now of course it is up to you to interpret that object according to your specific "business logic", and render a page that you think contains the required information.

Upvotes: 5

Related Questions