Making Authenticated Requests
This lesson reveals you how to authenticate yourself to an API endpoint you want to use. Therefore, the
auth parameter provided by each related
requests function is used. By default it uses HTTP’s Basic access authentication scheme, but you can use other methods as well. You can even use your own authentication method. This lesson covers even that.
Authentication is passed through the
requests uses the parameter
auth= and the username and password are passed as a tuple. By default, it will use the HTTP Basic authentication scheme, and I’ve included a link here to the article on Basic access.
Let’s check it out. So back here in the REPL, let’s make sure—if you haven’t already done it—to make sure that
requests is imported, and we’re going to import one additional thing. From the standard library we’ll import
getpass will prompt us to enter in a password after we call its function. For this example, we’re going to use GitHub and the
/user endpoint, so let’s save that URL to save us some time. To get there, it’s
api.github.com/user, and that will normally prompt you for a username and a password.
01:09 If you have a GitHub account, you simply use your username right here, and as a tuple you can enter in the username and the password. In this case, I’m going to have it prompt me to enter in the password. And let me close everything off here. Here’s where it’s going to prompt me.
There we go. Successful. As you can see, if I was to type the password wrong, I would get
<Response >, which I saw before, which is saying status code
Unauthorized. It’d be the same thing if I just simply tried to go to the URL by itself without putting any authorization in. I’d get the same thing—that we’re unauthorized. Again, it’s using the HTTP Basic authentication scheme under the hood.
You can explore those a little bit further on your own. You can even supply your own authentication mechanism if you want to, but to do that, you first have to create a subclass of
AuthBase inside of the
requests package, so let’s try it out. We need to create a file.
We’ll use the
httpbin service again for this example. This time, under
auth it will equal our
TokenAuth(), and we’ll just put a generic token in here… and just to make sure it ran, we got a
response—we’ll print it out. Let’s save. So again, importing
AuthBase from the
auth portion of
requests. And then again, we’re adding this
TokenAuth class and after initializing it, for the
.__call__() we’re adding this header with this
Oh, I need a request type,
get()—that will help. All right, let’s try it again. Great! And we successfully tested our custom authorization. Creating a bad authentication mechanism can create a security vulnerability, so unless a service really requires you to create something custom, it’s usually better to go ahead and use tried and true stuff like Basic auth or OAuth. Next, let’s talk about SSL Certificates.
Become a Member to join the conversation.