from typing import Optional
import requests
import copy


def build_session(
        session: Optional[requests.Session] = None,
        api_key: Optional[str] = None,
) -> requests.Session:
    """ Build session and reconcile passing of api key via arg or via session

    If an api key is included in the session headers, and passed through the
    `api_key` arg, then the value in the session headers will be overwritten
    temporarily for this request.
    """
    if api_key and session:
        session = copy.deepcopy(session)
    if session is None:
        session = requests.Session()
    if api_key:
        session.headers['x-api-key'] = api_key
    return session