python requests base url

Python Requests Base URL

When working with APIs or HTTP requests in Python, it is common to use a base URL as a starting point for all requests. The base URL is the beginning of the URL that is common to all requests made to a particular API.

Setting the Base URL

In Python Requests, the base URL can be set using the requests.Session() object. This allows you to set a default value for the url parameter for all requests made using that session.


import requests

s = requests.Session()
s.headers.update({'Authorization': 'Bearer '})
s.auth = ('user', 'pass')
s.verify = False

s.get('https://example.com/api/v1/users')

Alternatively, you can set the base URL using the requests.Request() object. This allows you to specify the base URL for all requests made using that request object.


import requests

url = 'https://example.com/api/v1/'

req = requests.Request('GET', url+'users')
prepared = req.prepare()

print(prepared.url) # https://example.com/api/v1/users

Using the Base URL in Requests

Once you have set the base URL, you can make requests to specific endpoints by appending the endpoint to the base URL.


import requests

url = 'https://example.com/api/v1/'

response = requests.get(url+'users')

print(response.json())

You can also use relative URLs when making requests. In this case, the relative URL will be appended to the base URL.


import requests

s = requests.Session()
s.headers.update({'Authorization': 'Bearer '})
s.auth = ('user', 'pass')
s.verify = False

response = s.get('/users')

print(response.json())

It is recommended to always use the base URL when making requests to an API to ensure consistency and make the code more readable and maintainable.