How to build URLs in Python with the standard library?

python

Solution

`urlparse` in the python standard library is all about building valid urls. Check the documentation of urlparse

Example:

from collections import namedtuple
from urllib.parse import urljoin, urlencode, urlparse, urlunparse

# namedtuple to match the internal signature of urlunparse
Components = namedtuple(
    typename='Components', 
    field_names=['scheme', 'netloc', 'url', 'path', 'query', 'fragment']
)

query_params = {
    'param1': 'some data', 
    'param2': 42
}

url = urlunparse(
    Components(
        scheme='https',
        netloc='example.com',
        query=urlencode(query_params),
        path='',
        url='/',
        fragment='anchor'
    )
)

print(url)

Output:

https://example.com/?param1=some+data&param2=42#anchor

Problem

Many languages have standard APIs for building and parsing URLS from - or into parts like scheme, host, port, query-param. Some allow me to start with a base URL and add paths. How do I do this in python using the standard library? For example, how would I build the URL: ``` http://subdomain.domain.com?arg1=someargument&arg2=someotherargument ``` given a base of `"http://subdomain.domain.com"` and some query params. Or given the scheme: `"http"`, the host `"subdomain.domain.com"`, etc?

Original source