Skip to content

Downloads court opinions from CourtListener and reads them.

CourtListener (https://www.courtlistener.com) is a free legal research site run by the Free Law Project. CourtListener downloads its opinions in two ways (its "method"):

  • "bulk" (the default) extracts them from the bulk data files, which need no key and have no limits, but are very large and are updated every three months.
  • "api" downloads them with the REST API, which needs an API key (see courtpy.secrets). It is best for small or very recent sets of cases, because CourtListener limits how many requests an account can make (a free account can make 5 a minute, 50 an hour, and 125 a day, as of 2026). The client waits when asked to, saves its place, and resumes where it stopped when it is run again.

Both save each case as a JSON file named for its CourtListener cluster id, in a folder named for its court (such as "courtlistener/ca1/4567890.json"), which read_case turns into a Case for parsing.

The bulk data is published every three months (on the last day of March, June, September, and December), in a public bucket: https://com-courtlistener-storage.s3-us-west-2.amazonaws.com/list.html?prefix=bulk-data/

Five files hold what courtpy needs, and every one is always read, so that each case is put in the court of its docket:

File Size (2026) Holds
courts < 1 MB Each court's name and jurisdiction.
dockets about 5 GB Each case's court, docket number, and dates.
opinion-clusters about 2.5 GB Each decision's parties, judges, date, and status.
citations about 130 MB Each decision's reporter citations.
opinions about 55 GB The text of each opinion.

They are read in that order, keeping the cases of the courts and dates asked for, and each case is saved in the same form as the API's, so the same parser reads both. Every case is saved with its whole docket (all of its fields but those in options._DOCKET_SKIPPED), so the dockets file is read twice: first to find which dockets belong to the courts, and again, once the cases are known, to keep the dockets of those cases alone. Reading the opinions file takes hours, so it is worth extracting every court and year you may need at once.

The files are read with amos.loaders.read_chunks, which decompresses and parses them on every core and keeps only the rows asked for. By default, they are downloaded first (to a folder outside of any project, see courtpy.utilities.data_folder) with amos.loaders.download_file and kept, so that they can be used again and an interrupted download resumes. With stream = True, they are read straight from the bucket instead, which needs no disk space but starts over if the connection fails.

Contents

DOWNLOAD_METHODS: the ways that CourtListener.download can download. CourtListener: downloads cases from CourtListener's bulk data or API. CourtListenerSource: reads cases saved by CourtListener. CourtListenerError: raised when the API returns an error. RateLimitError: raised when the API asks for a longer pause than allowed. add_opinions: adds opinions to a saved case. case_path: returns the path of a saved case. citation_strings: returns citations as text. is_complete: returns whether a case was saved with its opinions. opinion_role: classifies an opinion as majority, concurrence, or dissent. opinion_text: returns the plain text of an opinion. read_case: reads a saved case for parsing. save_case: saves a case. slim_opinion: keeps one field of an opinion's text, to save space. logger: the module's logger, which reports the progress of downloads, of reading the bulk files, and pauses asked for by CourtListener.

CourtListener(api_key=None, api_url=options._API_URL, bulk_url=options._BULK_URL, bulk_folder=None, bulk_date=None, stream=False, min_interval=options._MIN_INTERVAL, max_wait=options._MAX_WAIT, timeout=options._TIMEOUT, session=None) dataclass

Downloads cases from CourtListener's bulk data or its REST API.

download takes the "method" to download with: "bulk" (the default), which extracts the cases from the bulk data files and needs no key, or "api", which downloads them with the REST API (version 4).

Every request to the API includes the API key, which is found with courtpy.secrets.get_api_key when the first request is made if it was not passed, so the bulk data can be used without a key. Requests to the API are spaced at least min_interval seconds apart. If CourtListener asks for a pause (an HTTP 429 response), the client waits as long as it is asked, up to max_wait seconds. A longer pause (such as the daily limit) raises a RateLimitError, and download can be run again later to resume.

Parameters:

Name Type Description Default
api_key str | None

a CourtListener API key. Defaults to None, in which case it is found with courtpy.secrets.get_api_key when it is needed.

None
api_url str

address of the API. Defaults to options._API_URL.

_API_URL
bulk_url str

address of the bucket of bulk data. Defaults to options._BULK_URL.

_BULK_URL
bulk_folder Path | str | None

folder to keep the downloaded bulk files in. Defaults to None, in which case "bulk" in utilities.data_folder() is used.

None
bulk_date str | None

the date of the bulk files to use, as YYYY-MM-DD. Defaults to None, in which case the newest files are used (and it is set when they are found, see resolve_bulk_date).

None
stream bool

whether to read the bulk files straight from the bucket instead of downloading them. Defaults to False.

False
min_interval float

fewest seconds between requests to the API. Defaults to options._MIN_INTERVAL.

_MIN_INTERVAL
max_wait float

most seconds to wait when the API asks for a pause. Defaults to options._MAX_WAIT.

_MAX_WAIT
timeout float

seconds to wait for a response. Defaults to options._TIMEOUT.

_TIMEOUT
session Any

an object with a get method like a requests.Session. Defaults to None, in which case a requests.Session that identifies courtpy is made.

None

Attributes:

Name Type Description
requests_made int

number of requests made to the API by this client.

_courts dict[str, dict[str, Any]]

information about each court that has been looked up (see court), by its id, so that each court is asked for only once.

_last_request float

when the last request was made, from time.monotonic, so that the next one can wait until min_interval seconds have passed. It is 0 before the first request.

bulk_dates(kind='opinions')

Returns the dates of the bulk files of one kind in the bucket.

Parameters:

Name Type Description Default
kind str

"courts", "dockets", "opinion-clusters", "citations", or "opinions". Defaults to "opinions".

'opinions'

Returns:

Type Description
list[str]

The dates, from oldest to newest.

Source code in src/courtpy/sources/courtlistener.py
def bulk_dates(self, kind: str = 'opinions') -> list[str]:
    """Returns the dates of the bulk files of one kind in the bucket.

    Args:
        kind: "courts", "dockets", "opinion-clusters", "citations", or
            "opinions". Defaults to "opinions".

    Returns:
        The dates, from oldest to newest.

    """
    dates = []
    for key in self._list_bucket(f'{options._BULK_PREFIX}{kind}-'):
        match = _BULK_DATE.search(key)
        # Skips files whose kind only starts with `kind` (such as
        # "opinions-cited" for "opinions").
        if match and key == (
            f'{options._BULK_PREFIX}{kind}-{match.group(1)}.csv.bz2'):
            dates.append(match.group(1))
    return sorted(set(dates))

court(court)

Returns information about a court.

Parameters:

Name Type Description Default
court str

a CourtListener court id, such as "ca1".

required

Returns:

Type Description
dict[str, Any]

The court's "id", "full_name", "short_name", "citation_string", and "jurisdiction" (such as "F" for federal appellate courts).

Source code in src/courtpy/sources/courtlistener.py
def court(self, court: str) -> dict[str, Any]:
    """Returns information about a court.

    Args:
        court: a CourtListener court id, such as "ca1".

    Returns:
        The court's "id", "full_name", "short_name", "citation_string",
            and "jurisdiction" (such as "F" for federal appellate courts).

    """
    if court not in self._courts:
        fields = 'id,full_name,short_name,citation_string,jurisdiction'
        self._courts[court] = self.get(
            f'courts/{court}/', {'fields': fields})
    return self._courts[court]

download(courts, start_date=None, end_date=None, folder='courtlistener', *, method='bulk', max_cases=None, dockets=False, refresh=False)

Downloads the cases of courts filed between two dates.

With "bulk", the bulk files are read in turn (see the module's documentation), and the cases that were already saved with their opinions are skipped. Every case is saved with its docket.

With "api", each page of cases (opinion clusters) takes one request, and their opinions take one more (or more, if they have many opinions). Cases that were already saved (with their opinions) are skipped, and the place in each court's list of cases is saved, so running a download again resumes it. Running a finished download again takes one request for each court and saves any cases added to CourtListener since.

Parameters:

Name Type Description Default
courts str | Iterable[str]

CourtListener court ids (such as "ca1") or names of groups of them (such as "federal_appellate").

required
start_date str | None

earliest date filed, as YYYY-MM-DD. Defaults to None (no earliest date).

None
end_date str | None

latest date filed, as YYYY-MM-DD. Defaults to None (no latest date).

None
folder Path | str

folder to save the cases in. Defaults to "courtlistener".

'courtlistener'
method str

"bulk" or "api" (see DOWNLOAD_METHODS), in any case. Defaults to "bulk".

'bulk'
max_cases int | None

most cases to save: in all with "bulk", and in each court with "api". Defaults to None (every case).

None
dockets bool

with "api", whether to also download each case's docket (every field but those in options._DOCKET_SKIPPED, such as its docket number, dates, and the court appealed from). This takes one more request for each case. Defaults to False. The bulk data always includes the docket.

False
refresh bool

whether to download cases that were already saved. Defaults to False.

False

Raises:

Type Description
ValueError

if method is not one of DOWNLOAD_METHODS, or if no courts are named.

RateLimitError

if CourtListener asks for a pause longer than max_wait. What was downloaded is kept.

Returns:

Type Description
list[Path]

The paths of the cases saved (or updated) in this run.

Source code in src/courtpy/sources/courtlistener.py
def download(
    self,
    courts: str | Iterable[str],
    start_date: str | None = None,
    end_date: str | None = None,
    folder: pathlib.Path | str = 'courtlistener',
    *,
    method: str = 'bulk',
    max_cases: int | None = None,
    dockets: bool = False,
    refresh: bool = False) -> list[pathlib.Path]:
    """Downloads the cases of `courts` filed between two dates.

    With "bulk", the bulk files are read in turn (see the module's
    documentation), and the cases that were already saved with their
    opinions are skipped. Every case is saved with its docket.

    With "api", each page of cases (opinion clusters) takes one request,
    and their opinions take one more (or more, if they have many
    opinions). Cases that were already saved (with their opinions) are
    skipped, and the place in each court's list of cases is saved, so
    running a download again resumes it. Running a finished download
    again takes one request for each court and saves any cases added to
    CourtListener since.

    Args:
        courts: CourtListener court ids (such as "ca1") or names of groups
            of them (such as "federal_appellate").
        start_date: earliest date filed, as YYYY-MM-DD. Defaults to `None`
            (no earliest date).
        end_date: latest date filed, as YYYY-MM-DD. Defaults to `None` (no
            latest date).
        folder: folder to save the cases in. Defaults to "courtlistener".
        method: "bulk" or "api" (see `DOWNLOAD_METHODS`), in any case.
            Defaults to "bulk".
        max_cases: most cases to save: in all with "bulk", and in each
            court with "api". Defaults to `None` (every case).
        dockets: with "api", whether to also download each case's docket
            (every field but those in `options._DOCKET_SKIPPED`, such as
            its docket number, dates, and the court appealed from). This
            takes one more request for each case. Defaults to `False`.
            The bulk data always includes the docket.
        refresh: whether to download cases that were already saved.
            Defaults to `False`.

    Raises:
        ValueError: if `method` is not one of `DOWNLOAD_METHODS`, or if no
            courts are named.
        RateLimitError: if CourtListener asks for a pause longer than
            `max_wait`. What was downloaded is kept.

    Returns:
        The paths of the cases saved (or updated) in this run.

    """
    chosen = str(method).strip().lower()
    if chosen not in DOWNLOAD_METHODS:
        names = ' or '.join(f'"{m}"' for m in DOWNLOAD_METHODS)
        message = f'method must be {names}, not {method!r}'
        raise ValueError(message)
    wanted = utilities.expand_courts(courts)
    folder = pathlib.Path(folder)
    if chosen == 'bulk':
        return self._download_from_bulk_data(
            wanted, start_date, end_date, folder,
            max_cases = max_cases, refresh = refresh)
    saved: list[pathlib.Path] = []
    for court in wanted:
        saved.extend(self._download_court(
            court, start_date, end_date, folder,
            max_cases = max_cases, dockets = dockets,
            refresh = refresh))
    logger.info(
        'saved %d cases in %s with %d requests', len(saved), folder,
        self.requests_made)
    return saved

download_case(cluster_id, folder='courtlistener')

Downloads one case by its CourtListener cluster id.

This takes four requests: the case, its opinions, its docket (which names its court), and its court (unless another case from the same court was downloaded by this client).

Parameters:

Name Type Description Default
cluster_id int | str

the id of the opinion cluster (the number in the case's CourtListener address, after "/opinion/").

required
folder Path | str

folder to save the case in. Defaults to "courtlistener".

'courtlistener'

Returns:

Type Description
Path

The path of the saved case.

Source code in src/courtpy/sources/courtlistener.py
def download_case(
    self,
    cluster_id: int | str,
    folder: pathlib.Path | str = 'courtlistener') -> pathlib.Path:
    """Downloads one case by its CourtListener cluster id.

    This takes four requests: the case, its opinions, its docket (which
    names its court), and its court (unless another case from the same
    court was downloaded by this client).

    Args:
        cluster_id: the id of the opinion cluster (the number in the
            case's CourtListener address, after "/opinion/").
        folder: folder to save the case in. Defaults to "courtlistener".

    Returns:
        The path of the saved case.

    """
    cluster = self.get(f'clusters/{cluster_id}/')
    opinions = self._opinions_of([int(cluster['id'])])
    return self._save(
        cluster, opinions.get(int(cluster['id']), []), pathlib.Path(folder),
        court = None, docket = True)

fetch_bulk_file(kind)

Downloads one bulk file, resuming a download that was interrupted.

The file is downloaded with amos.loaders.download_file, which writes it beside its path (with ".part" added) until it is whole, so a file in the bulk folder is always complete.

Parameters:

Name Type Description Default
kind str

"courts", "dockets", "opinion-clusters", "citations", or "opinions".

required

Raises:

Type Description
OSError

if the download stopped before the whole file arrived (run it again to resume).

HTTPError

if the file cannot be downloaded.

Returns:

Type Description
Path

The path of the downloaded file.

Source code in src/courtpy/sources/courtlistener.py
def fetch_bulk_file(self, kind: str) -> pathlib.Path:
    """Downloads one bulk file, resuming a download that was interrupted.

    The file is downloaded with `amos.loaders.download_file`, which
    writes it beside its path (with ".part" added) until it is whole, so
    a file in the bulk folder is always complete.

    Args:
        kind: "courts", "dockets", "opinion-clusters", "citations", or
            "opinions".

    Raises:
        OSError: if the download stopped before the whole file arrived
            (run it again to resume).
        requests.HTTPError: if the file cannot be downloaded.

    Returns:
        The path of the downloaded file.

    """
    name = self._bulk_name(kind)
    folder = self._bulk_folder_path()
    path = folder / name
    if not path.is_file():
        logger.info('downloading %s to %s', name, folder)
    return amos.loaders.download_file(
        self._bulk_file_url(kind),
        path,
        timeout = self.timeout,
        session = self.session,
        resume = True)

fetch_pdf_headers(paths, *, refresh=False, delay=None, workers=4)

Saves the first page of each case's PDF, from its court's website.

CourtListener's text of many opinions starts after their header, so it lacks the panel ("Before: FERNANDEZ, GOULD, and M. SMITH, Circuit Judges"), and its list of judges may give only their last names, which two judges of a court can share. The court's own PDF of the opinion has the header on its first page. For each saved case, the PDF at its first opinion's "download_url" is downloaded, the text of its first page is saved in the case's file as "pdf_header" (with "pdf_header_status"), and the PDF is not kept. read_case makes it a section of its own, which the rule that finds the panel reads after the opinion's opening.

The requests to each website are made one at a time, delay seconds apart, and up to workers websites are asked at once. The API key is never sent. A case whose file already has a header (or a status, if its PDF could not be read) is skipped unless refresh is true.

Parameters:

Name Type Description Default
paths Iterable[Path | str]

paths of saved cases.

required
refresh bool

whether to fetch the PDF of a case again. Defaults to False.

False
delay float | None

seconds between requests to one website. Defaults to None, which uses options._PDF_DELAY.

None
workers int

websites to ask at once. With 1, every request is made with session; otherwise each website gets a session of its own. Defaults to 4.

4

Returns:

Type Description
DataFrame

A row for each case, with its "path", "url", and "status": "ok", "saved before", "no url", "http {code}" (such as "http 404"), "not a pdf", "unreadable", or "failed: {error}".

Source code in src/courtpy/sources/courtlistener.py
def fetch_pdf_headers(
    self,
    paths: Iterable[pathlib.Path | str],
    *,
    refresh: bool = False,
    delay: float | None = None,
    workers: int = 4) -> pd.DataFrame:
    """Saves the first page of each case's PDF, from its court's website.

    CourtListener's text of many opinions starts after their header, so
    it lacks the panel ("Before: FERNANDEZ, GOULD, and M. SMITH, Circuit
    Judges"), and its list of judges may give only their last names,
    which two judges of a court can share. The court's own PDF of the
    opinion has the header on its first page. For each saved case, the
    PDF at its first opinion's "download_url" is downloaded, the text of
    its first page is saved in the case's file as "pdf_header" (with
    "pdf_header_status"), and the PDF is not kept. `read_case` makes it a
    section of its own, which the rule that finds the panel reads after
    the opinion's opening.

    The requests to each website are made one at a time, `delay` seconds
    apart, and up to `workers` websites are asked at once. The API key is
    never sent. A case whose file already has a header (or a status, if
    its PDF could not be read) is skipped unless `refresh` is true.

    Args:
        paths: paths of saved cases.
        refresh: whether to fetch the PDF of a case again. Defaults to
            `False`.
        delay: seconds between requests to one website. Defaults to
            `None`, which uses `options._PDF_DELAY`.
        workers: websites to ask at once. With 1, every request is made
            with `session`; otherwise each website gets a session of its
            own. Defaults to 4.

    Returns:
        A row for each case, with its "path", "url", and "status": "ok",
            "saved before", "no url", "http {code}" (such as "http 404"),
            "not a pdf", "unreadable", or "failed: {error}".

    """
    pause = options._PDF_DELAY if delay is None else float(delay)
    rows: list[dict[str, Any]] = []
    hosts: dict[str, list[tuple[pathlib.Path, dict[str, Any], str]]] = {}
    for path in (pathlib.Path(p) for p in paths):
        record = json.loads(path.read_text(encoding = 'utf-8'))
        url = _pdf_url(record)
        if 'pdf_header_status' in record and not refresh:
            status = 'saved before'
        elif not url:
            status = 'no url'
        else:
            host = urllib.parse.urlparse(url).netloc
            hosts.setdefault(host, []).append((path, record, url))
            continue
        rows.append({'path': str(path), 'url': url, 'status': status})

    def fetch(
        cases_of_host: list[tuple[pathlib.Path, dict[str, Any], str]],
        session: Any) -> list[dict[str, Any]]:
        """Fetches the PDFs of one website's cases, one at a time.

        Args:
            cases_of_host: the path, record, and PDF's address of each
                case.
            session: the session to request them with.

        Returns:
            A row for each case.

        """
        done = []
        for place, (path, record, url) in enumerate(cases_of_host):
            if place:
                time.sleep(pause)
            text, status = _fetch_pdf_header(session, url, self.timeout)
            record['pdf_header'] = text
            record['pdf_header_status'] = status
            save_case(path, record)
            done.append({'path': str(path), 'url': url, 'status': status})
        return done

    groups = list(hosts.values())
    if int(workers) <= 1:
        for group in groups:
            rows.extend(fetch(group, self.session))
    else:
        with concurrent.futures.ThreadPoolExecutor(
            max_workers = int(workers)) as pool:
            jobs = [
                pool.submit(fetch, group, utilities.open_session())
                for group in groups]
            for job in jobs:
                rows.extend(job.result())
    table = pd.DataFrame(rows, columns = ['path', 'url', 'status'])
    logger.info(
        'fetched the PDF headers of %d cases: %s', len(table),
        table['status'].value_counts().to_dict())
    return table

get(path, params=None)

Returns the JSON response of one request to the API.

Parameters:

Name Type Description Default
path str

a path in the API (such as "clusters/") or a full address (such as the "next" page of a response).

required
params Mapping[str, Any] | None

query parameters. Defaults to None.

None

Raises:

Type Description
CourtListenerError

if the API returns an error, rejects the key, or cannot be reached after several tries.

MissingAPIKeyError

if no key was passed and none can be found (see courtpy.secrets.get_api_key).

RateLimitError

if the API asks for a pause longer than max_wait.

Returns:

Type Description
dict[str, Any]

The decoded JSON.

Source code in src/courtpy/sources/courtlistener.py
def get(
    self,
    path: str,
    params: Mapping[str, Any] | None = None) -> dict[str, Any]:
    """Returns the JSON response of one request to the API.

    Args:
        path: a path in the API (such as "clusters/") or a full address
            (such as the "next" page of a response).
        params: query parameters. Defaults to `None`.

    Raises:
        CourtListenerError: if the API returns an error, rejects the key,
            or cannot be reached after several tries.
        MissingAPIKeyError: if no key was passed and none can be found
            (see `courtpy.secrets.get_api_key`).
        RateLimitError: if the API asks for a pause longer than
            `max_wait`.

    Returns:
        The decoded JSON.

    """
    url = path if path.startswith('http') else urllib.parse.urljoin(
        self.api_url, path)
    headers = self._api_headers()
    failures = 0
    while True:
        self._space_requests()
        try:
            response = self.session.get(
                url, params = params, headers = headers,
                timeout = self.timeout)
        except requests.RequestException as error:
            failures += 1
            if failures > _RETRIES:
                message = f'CourtListener could not be reached: {error}'
                raise CourtListenerError(message) from error
            time.sleep(5 * 2 ** failures)
            continue
        finally:
            self.requests_made += 1
            self._last_request = time.monotonic()
        status = response.status_code
        if status == 429:
            wait = _retry_after(response)
            if wait > self.max_wait:
                raise RateLimitError(wait)
            logger.info(
                'CourtListener asked for a pause: waiting %.0f seconds',
                wait)
            time.sleep(wait)
            continue
        if status in _TEMPORARY and failures < _RETRIES:
            failures += 1
            time.sleep(5 * 2 ** failures)
            continue
        if status in (401, 403):
            message = (
                f'CourtListener rejected the request ({status}). Check '
                f'the API key with "courtpy key show". Details: '
                f'{_detail(response)}'
            )
            raise CourtListenerError(message)
        if status >= 400:
            message = (
                f'CourtListener returned {status}: {_detail(response)}')
            raise CourtListenerError(message)
        return dict(response.json())

pages(path, params=None)

Yields the results of each page of a list, and the next address.

Parameters:

Name Type Description Default
path str

a path in the API (such as "clusters/") or the address of a page.

required
params Mapping[str, Any] | None

query parameters for the first page. Defaults to None.

None

Yields:

Type Description
tuple[list[dict[str, Any]], str | None]

tuple[list[dict[str, Any]], str | None]: the results on each page and the address of the next page (or None after the last page).

Source code in src/courtpy/sources/courtlistener.py
def pages(
    self,
    path: str,
    params: Mapping[str, Any] | None = None) -> Iterator[
        tuple[list[dict[str, Any]], str | None]]:
    """Yields the results of each page of a list, and the next address.

    Args:
        path: a path in the API (such as "clusters/") or the address of a
            page.
        params: query parameters for the first page. Defaults to `None`.

    Yields:
        tuple[list[dict[str, Any]], str | None]: the results on each page
            and the address of the next page (or `None` after the last
            page).

    """
    url: str | None = path
    query = params
    while url:
        data = self.get(url, query)
        next_url = data.get('next')
        yield list(data.get('results', [])), next_url
        url, query = next_url, None

read_bulk_chunks(kind, *, columns=None, keep=None)

Yields chosen rows and columns of one bulk file, a chunk at a time.

The file is read with amos.loaders.read_chunks, which parses and decompresses it on every core and finds the rows in keep before any of their text becomes Python objects. If stream is true, the file is read from the bucket as it arrives, without being saved. Otherwise, it is downloaded first (or found in the bulk folder) with fetch_bulk_file.

Parameters:

Name Type Description Default
kind str

"courts", "dockets", "opinion-clusters", "citations", or "opinions".

required
columns Sequence[str] | None

the columns to return. Defaults to None, which returns every column.

None
keep Mapping[str, Any] | None

the values to keep of each of some columns, such as {'court_id': ['ca1']} (see amos.loaders.read_chunks). Defaults to None, which keeps every row.

None

Yields:

Type Description
DataFrame

pd.DataFrame: the rows of each chunk that are kept, with every value as text. Missing values are empty strs.

Source code in src/courtpy/sources/courtlistener.py
def read_bulk_chunks(
    self,
    kind: str,
    *,
    columns: Sequence[str] | None = None,
    keep: Mapping[str, Any] | None = None) -> Iterator[pd.DataFrame]:
    """Yields chosen rows and columns of one bulk file, a chunk at a time.

    The file is read with `amos.loaders.read_chunks`, which parses and
    decompresses it on every core and finds the rows in `keep` before
    any of their text becomes Python objects. If `stream` is true, the
    file is read from the bucket as it arrives, without being saved.
    Otherwise, it is downloaded first (or found in the bulk folder) with
    `fetch_bulk_file`.

    Args:
        kind: "courts", "dockets", "opinion-clusters", "citations", or
            "opinions".
        columns: the columns to return. Defaults to `None`, which
            returns every column.
        keep: the values to keep of each of some columns, such as
            `{'court_id': ['ca1']}` (see `amos.loaders.read_chunks`).
            Defaults to `None`, which keeps every row.

    Yields:
        pd.DataFrame: the rows of each chunk that are kept, with every
            value as text. Missing values are empty `str`s.

    """
    source = (
        self._bulk_file_url(kind) if self.stream
        else self.fetch_bulk_file(kind))
    yield from amos.loaders.read_chunks(
        source,
        columns = columns,
        keep = keep,
        double_quote = False,
        escape_char = '\\',
        session = self.session,
        timeout = self.timeout)

read_bulk_rows(kind, *, columns=None, keep=None)

Yields chosen rows of one bulk file.

Parameters:

Name Type Description Default
kind str

"courts", "dockets", "opinion-clusters", "citations", or "opinions".

required
columns Sequence[str] | None

the columns to return. Defaults to None, which returns every column.

None
keep Mapping[str, Any] | None

the values to keep of each of some columns (see read_bulk_chunks). Defaults to None, which keeps every row.

None

Yields:

Type Description
dict[str, str]

dict[str, str]: each row, mapping column names to text. Missing values are empty strs.

Source code in src/courtpy/sources/courtlistener.py
def read_bulk_rows(
    self,
    kind: str,
    *,
    columns: Sequence[str] | None = None,
    keep: Mapping[str, Any] | None = None) -> Iterator[dict[str, str]]:
    """Yields chosen rows of one bulk file.

    Args:
        kind: "courts", "dockets", "opinion-clusters", "citations", or
            "opinions".
        columns: the columns to return. Defaults to `None`, which
            returns every column.
        keep: the values to keep of each of some columns (see
            `read_bulk_chunks`). Defaults to `None`, which keeps every
            row.

    Yields:
        dict[str, str]: each row, mapping column names to text. Missing
            values are empty `str`s.

    """
    chunks = self.read_bulk_chunks(kind, columns = columns, keep = keep)
    for chunk in chunks:
        for row in chunk.to_dict('records'):
            yield {str(key): value for key, value in row.items()}

resolve_bulk_date()

Returns bulk_date, finding the newest complete set if needed.

Raises:

Type Description
LookupError

if no date has every kind of file that courtpy needs.

Returns:

Type Description
str

The date of the bulk files to use, as YYYY-MM-DD.

Source code in src/courtpy/sources/courtlistener.py
def resolve_bulk_date(self) -> str:
    """Returns `bulk_date`, finding the newest complete set if needed.

    Raises:
        LookupError: if no date has every kind of file that courtpy needs.

    Returns:
        The date of the bulk files to use, as YYYY-MM-DD.

    """
    if self.bulk_date is None:
        common: set[str] | None = None
        for kind in _BULK_KINDS:
            dates = set(self.bulk_dates(kind))
            common = dates if common is None else common & dates
        if not common:
            message = 'no date in the bulk data has every file needed'
            raise LookupError(message)
        self.bulk_date = max(common)
    return self.bulk_date

CourtListenerError

Bases: RuntimeError

Raised when the CourtListener API returns an error.

CourtListenerSource() dataclass

Bases: Source

Reads cases saved by CourtListener, from the bulk data or the API.

Each case is a JSON file (see read_case), whose sections come from its data, so no rules are needed to find them. The "courtlistener_header" rules find the parties and judges in them.

header = 'courtlistener_header' class-attribute

Required Methods

read(path)

Reads a saved case for parsing (see read_case).

Parameters:

Name Type Description Default
path Path

the path of the saved case.

required

Returns:

Type Description
Case

The case.

Source code in src/courtpy/sources/courtlistener.py
def read(self, path: pathlib.Path) -> cases.Case:
    """Reads a saved case for parsing (see `read_case`).

    Args:
        path: the path of the saved case.

    Returns:
        The case.

    """
    return read_case(path)

RateLimitError(seconds)

Bases: CourtListenerError

Raised when the API asks for a longer pause than courtpy will wait.

Its message says how long to wait and how to resume.

Parameters:

Name Type Description Default
seconds float

how long CourtListener asked courtpy to wait.

required
Source code in src/courtpy/sources/courtlistener.py
def __init__(self, seconds: float) -> None:  # noqa: D107
    self.seconds = seconds
    hours = seconds / 3600
    message = (
        f'CourtListener asked courtpy to wait {hours:.1f} hours before '
        f"making more requests (the account's limit was reached). Run "
        f'the same download again later: it resumes where it stopped. '
        f'The bulk data (method "bulk") has no limits.')
    super().__init__(message)

add_opinions(path, opinions)

Adds opinions to a saved case, replacing any with the same id.

Parameters:

Name Type Description Default
path Path

path of the saved case.

required
opinions Iterable[Mapping[str, Any]]

opinions to add.

required
Source code in src/courtpy/sources/courtlistener.py
def add_opinions(
    path: pathlib.Path,
    opinions: Iterable[Mapping[str, Any]]) -> None:
    """Adds opinions to a saved case, replacing any with the same id.

    Args:
        path: path of the saved case.
        opinions: opinions to add.

    """
    record = json.loads(path.read_text(encoding = 'utf-8'))
    existing = {o.get('id'): o for o in record.get('opinions', [])}
    for opinion in opinions:
        existing[opinion.get('id')] = dict(opinion)
    record['opinions'] = list(existing.values())
    save_case(path, record)

case_path(folder, court, cluster_id)

Returns the path of a saved case.

Parameters:

Name Type Description Default
folder Path | str

the folder of saved cases.

required
court str

the case's CourtListener court id.

required
cluster_id int | str

the case's CourtListener cluster id.

required

Returns:

Type Description
Path

"{folder}/{court}/{cluster_id}.json".

Source code in src/courtpy/sources/courtlistener.py
def case_path(
    folder: pathlib.Path | str,
    court: str,
    cluster_id: int | str) -> pathlib.Path:
    """Returns the path of a saved case.

    Args:
        folder: the folder of saved cases.
        court: the case's CourtListener court id.
        cluster_id: the case's CourtListener cluster id.

    Returns:
        "{folder}/{court}/{cluster_id}.json".

    """
    return pathlib.Path(folder) / court / f'{cluster_id}.json'

citation_strings(citations)

Returns citations as text, such as "123 F.3d 456".

Parameters:

Name Type Description Default
citations Iterable[Any]

citations from CourtListener: dicts with "volume", "reporter", and "page", or text.

required

Returns:

Type Description
list[str]

The citations as text.

Source code in src/courtpy/sources/courtlistener.py
def citation_strings(citations: Iterable[Any]) -> list[str]:
    """Returns citations as text, such as "123 F.3d 456".

    Args:
        citations: citations from CourtListener: `dict`s with "volume",
            "reporter", and "page", or text.

    Returns:
        The citations as text.

    """
    found = []
    for citation in citations or []:
        if isinstance(citation, Mapping):
            parts = (citation.get(k) for k in ('volume', 'reporter', 'page'))
            text = ' '.join(str(p) for p in parts if p not in (None, ''))
        else:
            text = str(citation)
        if text.strip():
            found.append(text.strip())
    return found

is_complete(path)

Returns whether a case was saved with at least one opinion.

Parameters:

Name Type Description Default
path Path

path of a saved case.

required

Returns:

Type Description
bool

Whether the file exists, can be read, and has an opinion.

Source code in src/courtpy/sources/courtlistener.py
def is_complete(path: pathlib.Path) -> bool:
    """Returns whether a case was saved with at least one opinion.

    Args:
        path: path of a saved case.

    Returns:
        Whether the file exists, can be read, and has an opinion.

    """
    if not path.is_file():
        return False
    try:
        record = json.loads(path.read_text(encoding = 'utf-8'))
    except (OSError, ValueError):
        return False
    return bool(record.get('opinions'))

opinion_role(kind)

Classifies an opinion by its CourtListener type.

Parameters:

Name Type Description Default
kind str | None

the opinion's "type", such as "010combined", "020lead", "030concurrence", "035concurrenceinpart", or "040dissent".

required

Returns:

Type Description
str

"majority" (combined, lead, unanimous, or plurality opinions, and opinions without a type), "concurrence", "dissent", "mixed" (an opinion concurring in part and dissenting in part), or "other" (such as an addendum).

Source code in src/courtpy/sources/courtlistener.py
def opinion_role(kind: str | None) -> str:
    """Classifies an opinion by its CourtListener type.

    Args:
        kind: the opinion's "type", such as "010combined", "020lead",
            "030concurrence", "035concurrenceinpart", or "040dissent".

    Returns:
        "majority" (combined, lead, unanimous, or plurality opinions, and
            opinions without a type), "concurrence", "dissent", "mixed" (an
            opinion concurring in part and dissenting in part), or "other"
            (such as an addendum).

    """
    text = (kind or '').lower()
    if not text:
        return 'majority'
    for fragment, role in _ROLES:
        if fragment in text:
            return role
    return 'other'

opinion_text(opinion)

Returns the plain text of an opinion.

Parameters:

Name Type Description Default
opinion Mapping[str, Any]

an opinion from CourtListener.

required

Returns:

Type Description
str

The text of the first field in options._TEXT_FIELDS that is not blank, converted from HTML or XML, or an empty str.

Source code in src/courtpy/sources/courtlistener.py
def opinion_text(opinion: Mapping[str, Any]) -> str:
    """Returns the plain text of an opinion.

    Args:
        opinion: an opinion from CourtListener.

    Returns:
        The text of the first field in `options._TEXT_FIELDS` that is not
            blank, converted from HTML or XML, or an empty `str`.

    """
    for field in options._TEXT_FIELDS:
        value = opinion.get(field)
        if isinstance(value, str) and value.strip():
            return amos.mungers.html_to_text(value)
    return ''

read_case(path)

Reads a saved CourtListener case for parsing.

The sections of text have the same names as the sections that rules find in Lexis-Nexis cases (such as "party", "history", "counsel", and "judges"), so that the same rules work for both. "court_num" and "court_name" are courtpy's number and name for the case's court, found by CourtListener's id for it in the table of courts of options._DEFAULT_JURISDICTION (see courtpy.courts.court_numbers_by_courtlistener_name), and "lower_court_num" and "lower_court_name" are those of the court appealed from, by the docket's id for it. Each is None if the table does not have the court (the header rules then look for the court appealed from in the history).

Parameters:

Name Type Description Default
path Path | str

path of a case saved by CourtListener.

required

Returns:

Type Description
Case

The case.

Source code in src/courtpy/sources/courtlistener.py
def read_case(path: pathlib.Path | str) -> cases.Case:
    """Reads a saved CourtListener case for parsing.

    The sections of text have the same names as the sections that rules find
    in Lexis-Nexis cases (such as "party", "history", "counsel", and
    "judges"), so that the same rules work for both. "court_num" and
    "court_name" are courtpy's number and name for the case's court, found
    by CourtListener's id for it in the table of courts of
    `options._DEFAULT_JURISDICTION` (see
    `courtpy.courts.court_numbers_by_courtlistener_name`), and
    "lower_court_num" and "lower_court_name" are those of the court appealed
    from, by the docket's id for it. Each is `None` if the table does not
    have the court (the header rules then look for the court appealed from
    in the history).

    Args:
        path: path of a case saved by `CourtListener`.

    Returns:
        The case.

    """
    path = pathlib.Path(path)
    record = json.loads(path.read_text(encoding = 'utf-8'))
    cluster = record.get('cluster') or {}
    docket = record.get('docket') or {}
    court = record.get('court') or {}
    opinions = sorted(
        record.get('opinions') or [],
        key = lambda o: (
            o.get('ordering_key') is None, o.get('ordering_key') or 0,
            str(o.get('type') or ''), o.get('id') or 0))
    roles = [opinion_role(o.get('type')) for o in opinions]

    def authors(*kinds: str) -> str:
        """Returns the authors of the case's opinions with some roles.

        Args:
            *kinds: roles of opinions (see `opinion_role`), such as
                "majority" or "dissent".

        Returns:
            The "author_str" of each opinion with one of those roles, one per
                line, leaving out blank ones.

        """
        return '\n'.join(
            str(o.get('author_str') or '').strip()
            for o, role in zip(opinions, roles, strict = True)
            if role in kinds and str(o.get('author_str') or '').strip())

    majority = [
        o for o, role in zip(opinions, roles, strict = True)
        if role == 'majority']
    texts = [opinion_text(o) for o in opinions]
    sections = {
        'party': _first(
            cluster.get('case_name_full'), docket.get('case_name_full'),
            cluster.get('case_name')),
        'court': _first(court.get('full_name'), court.get('id')),
        'docket_number': _first(docket.get('docket_number')),
        'citation': '; '.join(record.get('citations') or []),
        'history': '\n'.join(_texts(
            cluster.get('procedural_history'), cluster.get('history'),
            docket.get('appeal_from_str'))),
        'counsel': _first(cluster.get('attorneys')),
        'disposition': _first(cluster.get('disposition')),
        'judges': _first(cluster.get('judges'), docket.get('panel_str')),
        'opinion_by': authors('majority'),
        'concurring_lines': authors('concurrence', 'mixed'),
        'dissenting_lines': authors('dissent', 'mixed'),
        'posture': _first(cluster.get('posture')),
        'syllabus': _first(cluster.get('syllabus')),
        'pdf_header': _first(record.get('pdf_header')),
        'opinion': '\n\n'.join(t for t in texts if t)}
    sections = {
        k: amos.mungers.html_to_text(v) if '<' in v else v
        for k, v in sections.items() if v}
    date_filed = _first(cluster.get('date_filed'))
    status = _first(cluster.get('precedential_status'))
    court_id = court.get('id') or docket.get('court_id')
    lower_id = _court_id_from(
        docket.get('appeal_from_id') or docket.get('appeal_from'))
    numbers = courts.court_numbers_by_courtlistener_name(
        options._DEFAULT_JURISDICTION)
    names = courts.court_names_by_courtlistener_name(
        options._DEFAULT_JURISDICTION)
    metadata: dict[str, Any] = {
        'source': 'courtlistener',
        'cluster_id': cluster.get('id'),
        'docket_id': cluster.get('docket_id') or docket.get('id') or (
            _id_from_url(cluster.get('docket'))),
        'court': court_id,
        'court_num': numbers.get(str(court_id or '').lower()),
        'court_name': names.get(str(court_id or '').lower()),
        'lower_court_num': numbers.get(lower_id or ''),
        'lower_court_name': names.get(lower_id or ''),
        'case_name': _first(cluster.get('case_name')),
        'docket_number': sections.get('docket_number'),
        'citation': sections.get('citation'),
        'disposition': sections.get('disposition'),
        'judges': sections.get('judges'),
        'date_filed': date_filed or None,
        'date_argued': _first(docket.get('date_argued')) or None,
        'year': int(date_filed[:4]) if date_filed[:4].isdigit() else None,
        'precedential_status': status or None,
        'published': status.lower() == 'published' if status else None,
        'per_curiam': any(_true(o.get('per_curiam')) for o in majority),
        'opinions': len(opinions),
        'author_id': next(
            (o.get('author_id') for o in majority if o.get('author_id')), None),
        'panel_ids': [
            i for i in (_id_from_url(p) for p in cluster.get('panel') or [])
            if i is not None],
        'citation_count': cluster.get('citation_count'),
        'nature_of_suit': _first(
            cluster.get('nature_of_suit'), docket.get('nature_of_suit'))
            or None,
        'url': _url(cluster)}
    # Only cases of the Supreme Court have an id in the Supreme Court
    # Database, so other tables of cases get no column for it.
    if _first(cluster.get('scdb_id')):
        metadata['scdb_id'] = _first(cluster.get('scdb_id'))
    return cases.Case(
        id = str(cluster.get('id') or path.stem),
        source = 'courtlistener',
        sections = sections,
        metadata = metadata,
        path = path)

save_case(path, record)

Saves a case as a JSON file, replacing any file at path safely.

Parameters:

Name Type Description Default
path Path

path to save the case to. Its folder is created if needed.

required
record Mapping[str, Any]

the case: "source", "court", "cluster", "docket", "citations", and "opinions".

required
Source code in src/courtpy/sources/courtlistener.py
def save_case(path: pathlib.Path, record: Mapping[str, Any]) -> None:
    """Saves a case as a JSON file, replacing any file at `path` safely.

    Args:
        path: path to save the case to. Its folder is created if needed.
        record: the case: "source", "court", "cluster", "docket",
            "citations", and "opinions".

    """
    path.parent.mkdir(parents = True, exist_ok = True)
    temporary = path.with_suffix('.json.part')
    temporary.write_text(
        json.dumps(record, ensure_ascii = False), encoding = 'utf-8')
    temporary.replace(path)

slim_opinion(opinion)

Returns an opinion with only one field of text, to save space.

Parameters:

Name Type Description Default
opinion Mapping[str, Any]

an opinion from the API or the bulk data.

required

Returns:

Type Description
dict[str, Any]

The fields in _OPINION_KEPT that it has, and the first field in options._TEXT_FIELDS that is not blank.

Source code in src/courtpy/sources/courtlistener.py
def slim_opinion(opinion: Mapping[str, Any]) -> dict[str, Any]:
    """Returns an opinion with only one field of text, to save space.

    Args:
        opinion: an opinion from the API or the bulk data.

    Returns:
        The fields in `_OPINION_KEPT` that it has, and the first field in
            `options._TEXT_FIELDS` that is not blank.

    """
    slim = {k: opinion[k] for k in _OPINION_KEPT if k in opinion}
    if 'cluster_id' not in slim:
        slim['cluster_id'] = _cluster_id(opinion)
    for field in options._TEXT_FIELDS:
        value = opinion.get(field)
        if isinstance(value, str) and value.strip():
            slim[field] = value
            break
    return slim