import requests


def _fetch_seq_ensembl(ac, start_i=None, end_i=None):
    """Fetch sequence slice from Ensembl public REST interface.

    Args:
        ac (str): The accession of the sequence to fetch.
        start_i (int, optional): The start index (interbase coordinates) of the subsequence to fetch.
            Defaults to None.
        end_i (int, optional): The end index (interbase coordinates) of the subsequence to fetch. 
            Defaults to None.

    Returns:
        str: The requested (sub)sequence
    
    Raises:
        RequestException: if request is unsuccessful.
    
    Note:
        The Ensembl REST interface does not currently accept intervals, so this method
        slices the sequence locally.

    Examples:
        >> len(_fetch_seq_ensembl('ENSP00000288602'))
        766

        >> _fetch_seq_ensembl('ENSP00000288602',0,10)
        u'MAALSGGGGG'

        >> _fetch_seq_ensembl('ENSP00000288602')[0:10]
        u'MAALSGGGGG'

        >> ac = 'ENSP00000288602'
        >> _fetch_seq_ensembl(ac ,0, 10) == _fetch_seq_ensembl(ac)[0:10]
        True
    """ 

    url_fmt = "http://rest.ensembl.org/sequence/id/{ac}"
    url = url_fmt.format(ac=ac)
    r = requests.get(url, headers={"Content-Type": "application/json"})
    r.raise_for_status()
    seq = r.json()["seq"]
    return seq if (start_i is None or end_i is None) else seq[start_i:end_i]