python requests netrc

Python Requests Netrc: Storing Credentials Safely

If you're working with APIs that require authentication, it's best practice to store your credentials securely. One way to do this is by using a netrc file. In this blog post, we'll discuss what a netrc file is, how to create one, and how to use it with Python Requests.

What is a netrc file?

A netrc file is a simple text file used to store login credentials for various services. It's commonly used on Unix-based operating systems like Linux or macOS. Netrc files are stored in the user's home directory and have permissions set to protect them from prying eyes.

The format of a netrc file is straightforward. Each line contains either a single keyword or a single keyword-value pair. The following keywords are commonly used:

  • machine: the name of the remote server
  • login: the username to use when connecting
  • password: the password to use when connecting
  • account: the account name to use when connecting (optional)

Here's an example of a netrc file:


    machine example.com
    login john
    password secret
  

Creating a netrc file

To create a netrc file, open your terminal or command prompt and enter the following command:

touch ~/.netrc

This will create an empty netrc file in your home directory.

Next, you'll need to set the permissions of the file so that it's only readable by you:

chmod 600 ~/.netrc

Using netrc with Python Requests

Now that you have a netrc file, you can use it with Python Requests to make authenticated requests.

The Requests library provides a built-in method for reading netrc files called netrc(). Here's an example:


    import requests
    
    # Read netrc file
    from netrc import netrc
    secrets = netrc().authenticators('example.com')
    
    # Make authenticated request
    response = requests.get('https://example.com/api', auth=(secrets[0], secrets[2]))
  

In this example, we first import the Requests library and the netrc() method. We then use netrc() to read the credentials for the remote server named "example.com". Finally, we make a GET request to the API endpoint, passing the username and password as authentication credentials.

Alternatively, you can pass your netrc file directly to Requests using the Session() object:


    import requests
    
    # Create session object
    session = requests.Session()
    
    # Pass netrc file to session object
    session.netrc = True
    
    # Make authenticated request
    response = session.get('https://example.com/api')
  

In this example, we create a session object using the Session() method. We then enable the use of the netrc file by setting session.netrc = True. Finally, we make a GET request to the API endpoint using the session object.

Using a netrc file is a simple and secure way to store your credentials when working with APIs. By following these steps, you can ensure that your login information is kept safe and accessible only to you.