Congress.gov API in Python#

by Sebastian Shirk

Congress.gov: https://www.congress.gov

API Documentation: https://api.congress.gov

API GitHub: LibraryOfCongress/api.congress.gov

Reuse Policy and More Info: https://www.loc.gov/legal

These recipe examples were tested on August 27, 2024.

Setup#

Import Libraries#

import requests
import time
from pprint import pprint

API Key#

For this API you need an API key. You can get one by signing up for free at https://api.data.gov/signup/.

Save your API key in a file called api_key.py and import your key. We will also use a BASE_URL constant for the API.

from api_key import API_KEY
BASE_URL = 'https://api.congress.gov/v3/'

1. Retrieving Bill Data#

Get Recent Bills#

Get a list of recent bills as well as their provided information.

def get_recent_bills(limit=2):
    print("Recent Bills:")
    endpoint = f'bill?api_key={API_KEY}&format=json&limit={limit}'
    response = requests.get(BASE_URL + endpoint)
    if response.status_code == 200:
        bills = response.json()['bills']
        for bill in bills:
            print(f"Title: {bill['title']}")
            print(f"Text: {bill['latestAction']['text']}")
            print(f"Origin Chamber: {bill['originChamber']}")
            print(f"Action Date: {bill['latestAction']['actionDate']}")
            print(f"Update Date: {bill['updateDate']}")
            print(f"Number: {bill['number']}")
            print(f"Bill Type: {bill['type']}")
            print()
    else:
        print("Failed to fetch recent bills.")

# get_recent_bills(limit=num)
# Limit is optional, default is 2 with a max of 250
get_recent_bills()
Recent Bills:
Title: DETECT Fentanyl and Xylazine Act of 2024
Text: Placed on the Union Calendar, Calendar No. 531.
Origin Chamber: House
Action Date: 2024-08-23
Update Date: 2024-08-24
Number: 8663
Bill Type: HR

Title: Decoupling from Foreign Adversarial Battery Dependence Act
Text: Placed on the Union Calendar, Calendar No. 530.
Origin Chamber: House
Action Date: 2024-08-23
Update Date: 2024-08-24
Number: 8631
Bill Type: HR

Get Number of Bills in a Specified Time Frame#

Gather the number of bills that were introduced in a specified time frame as well as how many became public law.

This may take a while to run when spanning over certain months, so be prepared to wait if you run this block.

def get_bills(start_date, end_date, offset=0):
    endpoint = f'bill?api_key={API_KEY}&format=json&fromDateTime={start_date}&toDateTime={end_date}&limit=250&offset={offset}'
    response = requests.get(BASE_URL + endpoint)
    if response.status_code == 200:
        return response.json().get('bills', [])
    else:
        print(f"Failed to fetch bills. Status code: {response.status_code}")
        return []

def fetch_all_bills(start_date, end_date):
    all_bills = []
    offset = 0 
    max_requests = 10000
    request_count = 0
    
    while request_count < max_requests:
        bills = get_bills(start_date, end_date, offset)
        year = start_date.split('-')[0]
        month = start_date.split('-')[1]
        if not bills:
            break

        filtered_bills = []
        for bill in bills:
            action_date = bill.get('updateDate', {})
            if (year not in action_date):
                continue
            elif not bill['latestAction']['text'].lower().startswith('became public law'):
                filtered_bills.append(bill)
                continue
            else:
                filtered_bills.append(bill)
        
        all_bills.extend(filtered_bills)
        
        if len(bills) < 250:
            break
        
        offset += 250
        request_count += 1
        print(f"Offset: {offset}, Total Bills Collected: {len(all_bills)}, Total Bills Passed: {sum(1 for bill in all_bills if 'latestAction' in bill and bill['latestAction']['text'].lower().startswith('became public law'))}")
        time.sleep(1)
    
    if request_count >= max_requests:
        print(f"Reached the maximum number of requests ({max_requests}). Stopping further requests.")
    
    return all_bills

def count_bills(bills_data):
    total_bills = len(bills_data)
    passed_bills = sum(1 for bill in bills_data if 'latestAction' in bill and bill['latestAction']['text'].lower().startswith('became public law'))
    return total_bills, passed_bills

start_date = "2023-2-01T00%3A00%3A00Z"
end_date = "2023-2-28T23%3A59%3A59Z"
print(f"Fetching bills for {start_date} to {end_date}")
bills_data = fetch_all_bills(start_date, end_date)
total_bills, passed_bills = count_bills(bills_data)
print(f"Total bills: {total_bills}")
print(f"Passed bills: {passed_bills}")
Fetching bills for 2023-2-01T00%3A00%3A00Z to 2023-2-28T23%3A59%3A59Z
Total bills: 106
Passed bills: 68

Get Summaries of Recent Bills#

Get all information on given bills as well as their summaries. Summaries are given in HTML format.

def get_recent_summaries(limit=2):
    endpoint = f'summaries?api_key={API_KEY}&format=json&limit={limit}'
    response = requests.get(BASE_URL + endpoint)
    if response.status_code == 200:
        summaries = response.json()['summaries']
        for summary in summaries:
            print(f"Action Date: {summary['actionDate']}")
            pprint(summary['bill'])
            print("HTML output:")
            pprint(summary['text'])
            print()
    else:
        print("Failed to fetch recent summaries.")

# get_recent_summaries(limit=num)
# Limit is optional, default is 2 with a max of 250
get_recent_summaries()
Action Date: 2023-06-06
{'congress': 118,
 'number': '1835',
 'originChamber': 'Senate',
 'originChamberCode': 'S',
 'title': 'National Cybersecurity Awareness Act',
 'type': 'S',
 'updateDateIncludingText': '2024-08-27T20:23:11Z',
 'url': 'https://api.congress.gov/v3/bill/118/s/1835?format=json'}
HTML output:
('<p><strong>National Cybersecurity Awareness Act</strong></p><p>This bill '
 'requires the Cybersecurity and Infrastructure Security Agency (CISA) of the '
 'Department of Homeland Security to lead and coordinate federal efforts to '
 'promote national cybersecurity awareness and to establish a program for '
 'planning and coordinating federal cybersecurity awareness '
 'campaigns.</p><p>CISA must also inform nonfederal entities of voluntary '
 'cyber hygiene best practices, including information on how to prevent '
 'cyberattacks and mitigate cybersecurity risks.</p><p>Further, CISA shall '
 'consult with private sector entities, state, local, tribal, and territorial '
 'governments, academia, and civil society to</p><ul><li>promote cyber hygiene '
 'best practices, including by focusing on tactics that are cost effective and '
 'result in significant cybersecurity improvement;</li><li>promote awareness '
 'of cybersecurity risks and mitigation with respect to malicious applications '
 'on internet-connected devices;</li><li>help consumers identify products that '
 'are designed to support user and product security;</li><li>coordinate with '
 'other federal agencies and departments to promote relevant '
 'cybersecurity-related awareness activities and ensure the federal government '
 'is coordinated in communicating accurate and timely cybersecurity '
 'information; and</li><li>expand nontraditional outreach mechanisms to ensure '
 'that entities including low-income and rural communities, small and medium- '
 'sized businesses and institutions, and state, local, tribal, and territorial '
 'partners receive cybersecurity awareness outreach in an equitable '
 "manner.</li></ul><p>CISA must (1) report within 180 days after this bill's "
 'enactment and annually thereafter regarding the campaign program; and (2) '
 'develop and maintain a central repository for its resources, tools, and '
 'public communications that promote cybersecurity awareness.</p>')

Action Date: 2023-04-13
{'congress': 118,
 'number': '2586',
 'originChamber': 'House',
 'originChamberCode': 'H',
 'title': 'Noncontiguous Shipping Competition Act',
 'type': 'HR',
 'updateDateIncludingText': '2024-08-27T16:18:44Z',
 'url': 'https://api.congress.gov/v3/bill/118/hr/2586?format=json'}
HTML output:
('<p><strong>Noncontiguous Shipping Competition Act </strong></p><p>This bill '
 'revises coastwise laws, commonly known as the Jones Act, that govern '
 'domestic transportation of merchandise or passengers by vessels.</p><p>The '
 'Jones&nbsp;Act generally requires that a vessel transporting merchandise or '
 'passengers&nbsp;from one U.S. point to another U.S. point be (1) built in '
 'the United States, (2)&nbsp;at least 75% owned by U.S. citizens, and (3) '
 'mostly crewed by U.S. citizens. The act also includes several exemptions and '
 'exceptions.</p><p>The bill exempts carriage on a route in noncontiguous '
 'trade from Jones Act requirements unless (1) at least three owners or '
 'operators of coastwise qualified vessels regularly operate such a vessel on '
 'the route, (2) each of such owners or operators transports at least 20% of '
 'the volume of goods on that route, and (3) none of such owners or operators '
 'are under common ownership.&nbsp;(Generally, <em>noncontiguous trade</em> is '
 'trade between two U.S. points where at least one of the points is in Alaska, '
 'Hawaii, Puerto Rico, or an insular territory or U.S. '
 'possession.)</p><!--tinycomments|2.1|data:application/json;base64,eyJtY2UtY29udmVyc2F0aW9uXzEzODExNjYwNDIxNzI0MTYwNjkwMDY0Ijp7InVpZCI6Im1jZS1jb252ZXJzYXRpb25fMTM4MTE2NjA0MjE3MjQxNjA2OTAwNjQiLCJjb21tZW50cyI6W3sidWlkIjoibWNlLWNvbnZlcnNhdGlvbl8xMzgxMTY2MDQyMTcyNDE2MDY5MDA2NCIsImF1dGhvciI6ImNpc2VuYmVyZ0BsaWIubG9jLmdvdiIsImF1dGhvck5hbWUiOiJjaXNlbmJlcmdAbGliLmxvYy5nb3YiLCJjb250ZW50IjoiSSBtYWRlIHRoaXMgbGFuZ3VhZ2UgYnJvYWRlciBiZWNhdXNlIHRoZSBKb25lcyBBY3QgZ2VuZXJhbGx5IGFwcGxpZXMgdG8gdHJhbnNwb3J0YXRpb24gYmV0d2Vlbi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mdlZCB0byBcImEgdmVzc2VsXCIgdG8gY2xhcmlmeSB0aGF0IDc1JSBvZiBhIHZlc3NlbCdzIHN0b2NrIG11c3QgYmUgb3duZWQgYnkgVVMgY2l0aXplbnMsIG5vdCB0aGF0IDc1JSBvZiBhbGwgdmVzc2VscyBtdXN0IGJlIG93bmVkIGJ5IEFtZXJpY2FucyAoU2VlIHBhZ2UgMTAgb2YgdGhlIENSUyByZXBvcnQpLiIsImNyZWF0ZWRBdCI6IjIwMjQtMDgtMjdUMTY6MDY6NDYuMzI3WiIsIm1vZGlmaWVkQXQiOiIyMDI0LTA4LTI3VDE2OjA2OjQ2LjMyN1oifV19LCJtY2UtY29udmVyc2F0aW9uXzc2NTYxNDMwOTUxNzI0Nzc1MTM3NzA5Ijp7InVpZCI6Im1jZS1jb252ZXJzYXRpb25fNzY1NjE0MzA5NTE3MjQ3NzUxMzc3MDkiLCJjb21tZW50cyI6W3sidWlkIjoibWNlLWNvbnZlcnNhdGlvbl83NjU2MTQzMDk1MTcyNDc3NTEzNzcwOSIsImF1dGhvciI6InBsZXVuZ0BsaWIubG9jLmdvdiIsImF1dGhvck5hbWUiOiJwbGV1bmdAbGliLmxvYy5nb3YiLCJjb250ZW50IjoiU3dpdGNoZWQgdG8gdGhlIGJpbGwgdGV4dCBmb3Igc3BlY2lmaWNpdHkuIiwiY3JlYXRlZEF0IjoiMjAyNC0wOC0yN1QxNjoxMjoxNy43MDlaIiwibW9kaWZpZWRBdCI6IjIwMjQtMDgtMjdUMTY6MTI6MTcuNzA5WiJ9XX19-->')

Get Recent Amemdments#

Get a list of recent amendments as well as their provided information.

def get_recent_amendments(limit=5):
    endpoint = f'amendment?api_key={API_KEY}&format=json&limit={limit}'
    response = requests.get(BASE_URL + endpoint)
    if response.status_code == 200:
        amendments = response.json()['amendments']
        for amendment in amendments:
            if 'latestAction' not in amendment:
                continue
            print(f"Action Date: {amendment['latestAction']['actionDate']}")
            print(f"Text: {amendment['latestAction']['text']}")
            if 'purpose' in amendment:
                print(f"Purpose: {amendment['purpose']}")
            print(f"Number: {amendment['number']}")
            print(f"Type: {amendment['type']}")
            print()
    else:
        print("Failed to fetch recent amendments.")

print("Recent Amendments:")
# get_recent_amendments(limit=num)
# Limit is optional, default is 5 with a max of 250
get_recent_amendments()
Recent Amendments:
Action Date: 2024-08-01
Text: Amendment SA 3224 agreed to in Senate by Unanimous Consent.
Purpose: In the nature of a substitute.
Number: 3224
Type: SAMDT

2. Retrieving Treaty Data#

Get Recent Treaties#

Get a list of recent treaties as well as their provided information.

We’ll use the “Number” to get more information on a specific treaty in the next cell.

def get_recent_treaties(limit=2):
    endpoint = f'treaty?api_key={API_KEY}&format=json&limit={limit}'
    response = requests.get(BASE_URL + endpoint)
    if response.status_code == 200:
        treaties = response.json()['treaties']
        for treaty in treaties:
            print(f"Topic: {treaty['topic']}")
            print(f"Transmitted Date: {treaty['transmittedDate']}")
            print(f"Update Date: {treaty['updateDate']}")
            print(f"Congress Received: {treaty['congressReceived']}")
            print(f"Congress Considered: {treaty['congressConsidered']}")
            print(f"Number: {treaty['number']}")
            print()
    else:
        print("Failed to fetch recent treaties.")

print("Recent Treaties:")
# get_recent_treaties(limit=num)
# Limit is optional, default is 2 with a max of 250
get_recent_treaties()
Recent Treaties:
Topic: None
Transmitted Date: None
Update Date: 2024-04-17T14:13:22Z
Congress Received: 117
Congress Considered: None
Number: 7

Topic: Extradition
Transmitted Date: 2017-01-17T00:00:00Z
Update Date: 2024-03-08T09:49:30Z
Congress Received: 115
Congress Considered: 115
Number: 1

Get Detailed Information on Treaties#

Get detailed information on a specific treaty by using the “Number” from the previous cell.

Requires a specific treaty number and a specific congress number.

def get_treaty_details(congress_numbers):
    treaty_number = 1
    for congress in congress_numbers:
        while True:
            endpoint = f'treaty/{congress}/{treaty_number}?api_key={API_KEY}&format=json'
            response = requests.get(BASE_URL + endpoint)
            if response.status_code == 200:
                treaty = response.json()['treaty']
                print(f"Congress: {congress}")
                print(f"Treaty Number: {treaty_number}")
                print(f"Topic: {treaty['topic']}")
                print(f"Index Terms: {treaty['indexTerms']}")
                print(f"Number: {treaty['number']}")
                pprint(f"Resolution Text: {treaty['resolutionText']}")
                pprint(f"Title: {treaty['titles'][0]}")
                print(f"Transmitted Date: {treaty['transmittedDate']}")
                print(f"Update Date: {treaty['updateDate']}")
                print()
                treaty_number += 1
            else:
                print(f"No more treaties found for Congress {congress}.")
                print()
                break
        treaty_number = 1

print("Treaty Details:")
get_treaty_details(['117', '118'])
Treaty Details:
Congress: 117
Treaty Number: 1
Topic: International Law and Organization
Index Terms: [{'name': '117-1'}, {'name': 'Kigali'}, {'name': 'Kigali Amendment'}, {'name': 'Montreal'}, {'name': 'Montreal Protocol'}, {'name': 'amendment'}, {'name': 'ozone'}]
Number: 1
('Resolution Text: <p>As approved by the Senate:</p><br><p> '
 '</p><br><p>Resolved (two-thirds of the Senators present concurring therein), '
 '</p><br><p></p><br><p>SECTION 1. SENATE ADVICE AND CONSENT SUBJECT TO '
 'DECLARATIONS AND A CONDITION </p><br><br><p>\tThe Senate advises and '
 'consents to the ratification of the Amendment to the Montreal Protocol on '
 'Substances that Deplete the Ozone Layer (the “Montreal Protocol”), adopted '
 'at Kigali on October 15, 2016, by the Twenty-Eighth Meeting of the Parties '
 'to the Montreal Protocol (“The Kigali Amendment”) (Treaty Doc. 117-1), '
 'subject to the declarations of section 2 and the condition of section 3. '
 '</p><br><p></p><br><p>SECTION 2. DECLARATIONS</p><br><p></p><br><p>\tThe '
 'advice and consent of the Senate under section 1 is subject to the following '
 'declarations: </p><br><p>\t\t(1) The Kigali amendment is not '
 'self-executing.</p><br><p>(2) The People’s Republic of China is not a '
 'developing country, and the United Nations and other intergovernmental '
 'organizations should not treat the People’s Republic of China as '
 'such.</p><br><p></p><br><p>SEC. 3. CONDITION.</p><br><p></p><br><p>The '
 'advice and consent of the Senate under section 1 is subject to the following '
 'condition: Prior to the Thirty-Fifth Meeting of the Parties to the Montreal '
 'Protocol, the Secretary of State shall transmit to the Secretariat of the '
 'Vienna Convention for the Protection of the Ozone Layer a proposal to amend '
 'Decision I/12E, “Clarification of terms and definitions: developing '
 'countries,” made at the First Meeting of the Parties, to remove the People’s '
 'Republic of China.</p><br><br><br>')
("Title: {'title': 'Amendment to the Montreal Protocol on Substances that "
 'Deplete the Ozone Layer (the "Montreal Protocol"), adopted at Kigali on '
 'October 15, 2016, by the Twenty-Eighth Meeting of the Parties to the '
 'Montreal Protocol (the "Kigali Amendment").\', \'titleType\': \'Treaty - '
 "Formal Title'}")
Transmitted Date: 2021-11-16T00:00:00Z
Update Date: 2024-03-07T04:01:16Z

Congress: 117
Treaty Number: 2
Topic: Extradition and Criminal Assistance
Index Terms: [{'name': 'Albania'}, {'name': 'Extradition'}]
Number: 2
'Resolution Text: '
("Title: {'title': 'Extradition Treaty Between the Government of the United "
 "States of America and the Government of the Republic of Albania', "
 "'titleType': 'Treaty - Formal Title'}")
Transmitted Date: 2022-04-07T00:00:00Z
Update Date: 2023-03-07T12:19:25Z

Congress: 117
Treaty Number: 3
Topic: International Law and Organization
Index Terms: [{'name': 'Accession'}, {'name': 'Kingdom of Sweden'}, {'name': 'North Atlantic Treaty of 1949'}, {'name': 'Protocols'}, {'name': 'Republic of Finland'}, {'name': 'T.Doc.117-3'}]
Number: 3
('Resolution Text: <!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml" '
 'lang="en"><head><meta name="meta:creation-date" content="2022/08/03 '
 '18:28:08" /><meta name="dc:title" content="[117] TreatyRes. 6 for TreatyDoc. '
 '117 - 3" /><meta name="Creation-Date" content="2022/08/03 18:28:08" /><meta '
 'name="dcterms:created" content="2022/08/03 18:28:08" /><meta '
 'name="Content-Type" content="application/rtf" /><title>[117] TreatyRes. 6 '
 'for TreatyDoc. 117 - 3</title></head><body><p>As approved by the Senate: '
 '</p><p><i>Resolved (two-thirds of the Senators present concurring '
 'therein),</i></p><p></p><p><b>SECTION 1. SENATE ADVICE AND CONSENT SUBJECT '
 'TO DECLARATIONS AND CONDITIONS.</b></p><p></p><p>The Senate advises and '
 'consents to the ratification of the Protocols to the North Atlantic Treaty '
 'of 1949 on the Accession of the Republic of Finland and the Kingdom of '
 'Sweden, which were signed on July 5, 2022, by the United States of America '
 'and other parties to the North Atlantic Treaty of 1949 (Treaty Doc. 117-3), '
 'subject to the declarations of section 2 and the condition of section '
 '3.</p><p><b>SEC. 2. DECLARATIONS.</b></p><p></p><p>The advice and consent of '
 'the Senate under section 1 is subject to the following '
 'declarations:</p><p>(1)\tReaffirmation That United States Membership in NATO '
 'Remains a Vital National Security Interest of the United States.- The Senate '
 'declares that-</p><p>(A)\tfor more than 70 years the North Atlantic Treaty '
 'Organization (NATO) has served as the preeminent organization to defend the '
 'countries in the North Atlantic area against all external '
 'threats;</p><p>(B)\tthrough common action, the established democracies of '
 'North America and Europe that were joined in NATO persevered and prevailed '
 'in the task of ensuring the survival of democratic government in Europe and '
 'North America throughout the Cold War;</p><p>(C)\tNATO enhances the security '
 'of the United States by embedding European states in a process of '
 'cooperative security planning and by ensuring an ongoing and direct '
 'leadership role for the United States in European security '
 'affairs;</p><p>(D)\tthe responsibility and financial burden of defending the '
 'democracies of Europe and North America can be more equitably shared through '
 'an alliance in which specific obligations and force goals are met by its '
 'members;</p><p>(E)\tthe security and prosperity of the United States is '
 "enhanced by NATO's collective defense against aggression that may threaten "
 'the security of NATO members; and</p><p>(F)\tUnited States membership in '
 'NATO remains a vital national security interest of the United '
 'States.</p><p>(2)\tStrategic Rationale for NATO Enlargement.- The Senate '
 'declares that-</p><p>(A)\tthe United States and its NATO allies face '
 'continued threats to their stability and territorial integrity;</p><p>(B)\t'
 'an attack against Finland or Sweden, or the destabilization of either '
 'arising from external subversion, would threaten the stability of Europe and '
 'jeopardize United States national security interests;</p><p>(C)\tFinland and '
 'Sweden, having established democratic governments and having demonstrated a '
 'willingness to meet the requirements of membership, including those '
 'necessary to contribute to the defense of all NATO members, are in a '
 'position to further the principles of the North Atlantic Treaty and to '
 'contribute to the security of the North Atlantic area; and</p><p>(D)\t'
 'extending NATO membership to Finland and Sweden will strengthen NATO, '
 'enhance stability in Europe, and advance the interests of the United States '
 "and its NATO allies.</p><p>(3)\tSupport for NATO's Open Door Policy.- The "
 "policy of the United States is to support NATO's Open Door Policy that "
 'allows any European country to express its desire to join NATO and '
 'demonstrate its ability to meet the obligations of NATO '
 'membership.</p><p>(4)\tFuture Consideration of Candidates for Membership in '
 'NATO.-</p><p>(A)\tSenate Finding.-The Senate finds that the United States '
 'will not support the accession to the North Atlantic Treaty of, or the '
 'invitation to begin accession talks with, any European state (other than '
 'Finland and Sweden), unless-</p><p>(i)\tthe President consults with the '
 'Senate consistent with Article II, section 2, clause 2 of the Constitution '
 'of the United States (relating to the advice and consent of the Senate to '
 'the making of treaties); and</p><p>(ii)\tthe prospective NATO member can '
 'fulfill all of the obligations and responsibilities of membership, and the '
 'inclusion of such state in NATO would serve the overall political and '
 'strategic interests of NATO and the United States.</p><p>(B)\tRequirement '
 'for Consensus and Ratification.-The Senate declares that no action or '
 'agreement other than a consensus decision by the full membership of NATO, '
 'approved by the national procedures of each NATO member, including, in the '
 'case of the United States, the requirements of Article II, section 2, clause '
 '2 of the Constitution of the United States (relating to the advice and '
 'consent of the Senate to the making of treaties), will constitute a '
 'commitment to collective defense and consultations pursuant to Articles 4 '
 'and 5 of the North Atlantic Treaty.</p><p>(5)\tInfluence of Non-NATO Members '
 'on NATO Decisions.- The Senate declares that any country that is not a '
 'member of NATO shall have no impact on decisions related to NATO '
 'enlargement.</p><p>(6)\tSupport for 2014 Wales Summit Defense Spending '
 'Benchmark.--The Senate declares that all NATO members should spend a minimum '
 'of 2 percent of their Gross Domestic Product (GDP) on defense and 20 percent '
 'of their defense budgets on major equipment, including research and '
 'development, by 2024, as outlined in the 2014 Wales Summit '
 'Declaration.</p><p><b>SEC. 3. CONDITION.</b></p><p></p><p>The advice and '
 'consent of the Senate under section 1 is subject to the following '
 'conditions</p><p>(1)\tPresidential Certification.-Prior to the deposit of '
 'the instrument of ratification, the President shall certify to the Senate as '
 'follows:</p><p>(A)\tThe inclusion of Finland and Sweden in NATO will not '
 'have the effect of increasing the overall percentage share of the United '
 'States in the common budgets of NATO.</p><p>(B)\tThe inclusion of Finland '
 'and Sweden in NATO does not detract from the ability of the United States to '
 'meet or to fund its military requirements outside the North Atlantic '
 'area.</p><p><b>SEC. 4. DEFINITIONS.</b></p><p></p><p>In this '
 'resolution:</p><p>(1)\tNATO Members.-The term &ldquo;NATO members&rdquo; '
 'means all countries that are parties to the North Atlantic '
 'Treaty.</p><p>(2)\tNon-NATO Members.-The term &ldquo;non-NATO members&rdquo; '
 'means all countries that are not parties to the North Atlantic '
 'Treaty.</p><p>(3)\tNorth Atlantic Area.-The term &ldquo;North Atlantic '
 'Area&rdquo; means the area covered by Article 6 of the North Atlantic '
 'Treaty, as applied by the North Atlantic Council.</p><p>(4)\tNorth Atlantic '
 'Treaty.-The term &ldquo;North Atlantic Treaty&rdquo; means the North '
 'Atlantic Treaty, signed at Washington April 4, 1949 (63 Stat. 2241; TIAS '
 '1964), as amended.</p><p>(5)\tUnited States Instrument of Ratification.-The '
 'term &ldquo;United States instrument of ratification&rdquo; means the '
 'instrument of ratification of the United States of the Protocols to '
 'the</p><p>North Atlantic Treaty of 1949 on the Accession of the Republic of '
 'Finland and the Kingdom of Sweden.</p></body></html>')
("Title: {'title': 'Protocols to the North Atlantic Treaty of 1949 on the "
 "Accession of the Republic of Finland and the Kingdom of Sweden', "
 "'titleType': 'Treaty - Formal Title'}")
Transmitted Date: 2022-07-11T00:00:00Z
Update Date: 2023-03-07T12:19:24Z

No more treaties found for Congress 117.

Congress: 118
Treaty Number: 1
Topic: Maritime Boundaries and Claims
Index Terms: [{'name': 'Cuba'}, {'name': 'Maritime Boundaries'}, {'name': 'Mexico'}, {'name': 'TD 118-1'}, {'name': 'Treaty Doc. 118-1'}]
Number: 1
'Resolution Text: None'
("Title: {'title': 'The Treaty between the United States of America and the "
 'Republic of Cuba on the Delimitation of the Continental Shelf in the Eastern '
 'Gulf of Mexico beyond 200 Nautical Miles, and the Treaty between the '
 'Government of the United States of America and the Government of the United '
 'Mexican States on the Delimitation of the Maritime Boundary in the Eastern '
 'Gulf of Mexico, both of which were signed at Washington on January 18, '
 "2017', 'titleType': 'Treaty - Formal Title'}")
Transmitted Date: 2023-12-18T00:00:00Z
Update Date: 2023-12-19T04:01:18Z

No more treaties found for Congress 118.

3. Retrieving Data on Members of Congress#

Get Members of Congress#

Get a list of members of congress as well as their provided information.

def get_members_of_congress(limit=2):
    endpoint = f'member/?api_key={API_KEY}&format=json&limit={limit}'
    response = requests.get(BASE_URL + endpoint)
    if response.status_code == 200:
        members = response.json()['members']
        for member in members:
            print(f"Name: {member['name']}")
            print(f"Party: {member['partyName']}")
            print(f"State: {member['state']}")
            print(f"District: {member['district']}")
            print(f"Terms: {member['terms']}")
            print(f"Bioguide ID: {member['bioguideId']}")
            print()
    else:
        print("Failed to fetch members of Congress.")

print("Members of Congress:")
# get_members_of_congress(limit=num)
# Limit is optional, default is 2 with a max of 250
get_members_of_congress()
Members of Congress:
Name: Nowak, Henry
Party: Democratic
State: New York
District: 33
Terms: {'item': [{'chamber': 'House of Representatives', 'endYear': 1993, 'startYear': 1975}]}
Bioguide ID: N000163

Name: Pascrell, Bill
Party: Democratic
State: New Jersey
District: 9
Terms: {'item': [{'chamber': 'House of Representatives', 'endYear': 2024, 'startYear': 1997}]}
Bioguide ID: P000096

Get Members of Congress by State#

Get a list of members of congress by state as well as their provided information.

Requires a specific state abbreviation and a “True” or “False” to determine whether to get current or all members of that state.

def get_members_of_congress(state, current, limit=250):
    endpoint = f'member/{state}?api_key={API_KEY}&format=json&limit={limit}'
    response = requests.get(BASE_URL + endpoint)
    if response.status_code == 200:
        members = response.json()['members']
        for member in members:
            if current and 'endYear' in member['terms']['item'][0]:
                continue    
            print(f"Name: {member['name']}")
            print(f"Party: {member['partyName']}")
            print(f"State: {member['state']}")
            if 'district' in member:
                print(f"District: {member['district']}")
            else:
                print(f"District: N/A")
            print(f"Terms: {member['terms']}")
            print(f"Bioguide ID: {member['bioguideId']}")
            print()
    else:
        print("Failed to fetch members of Congress.")

print("Members of Congress:")
# get_members_of_congress('StateCode', bool, limit=num)
# bool = True for current members, False for former and current members
# Limit is optional, default is 250 to get all members
get_members_of_congress('AL', True)
Members of Congress:
Name: Strong, Dale W.
Party: Republican
State: Alabama
District: 5
Terms: {'item': [{'chamber': 'House of Representatives', 'startYear': 2023}]}
Bioguide ID: S001220

Name: Carl, Jerry L.
Party: Republican
State: Alabama
District: 1
Terms: {'item': [{'chamber': 'House of Representatives', 'startYear': 2021}]}
Bioguide ID: C001054

Name: Moore, Barry
Party: Republican
State: Alabama
District: 2
Terms: {'item': [{'chamber': 'House of Representatives', 'startYear': 2021}]}
Bioguide ID: M001212

Name: Palmer, Gary J.
Party: Republican
State: Alabama
District: 6
Terms: {'item': [{'chamber': 'House of Representatives', 'startYear': 2015}]}
Bioguide ID: P000609

Name: Sewell, Terri A.
Party: Democratic
State: Alabama
District: 7
Terms: {'item': [{'chamber': 'House of Representatives', 'startYear': 2011}]}
Bioguide ID: S001185

Name: Aderholt, Robert B.
Party: Republican
State: Alabama
District: 4
Terms: {'item': [{'chamber': 'House of Representatives', 'startYear': 1997}]}
Bioguide ID: A000055

Name: Rogers, Mike D.
Party: Republican
State: Alabama
District: 3
Terms: {'item': [{'chamber': 'House of Representatives', 'startYear': 2003}]}
Bioguide ID: R000575

Name: Britt, Katie Boyd
Party: Republican
State: Alabama
District: N/A
Terms: {'item': [{'chamber': 'Senate', 'startYear': 2023}]}
Bioguide ID: B001319

Name: Tuberville, Tommy
Party: Republican
State: Alabama
District: N/A
Terms: {'item': [{'chamber': 'Senate', 'startYear': 2021}]}
Bioguide ID: T000278

Get Legislation Sponsored and Cosponsored by a Member of Congress#

Get a list of legislation sponsored and cosponsored by a member of congress as well as their provided information.

Requires a specific congress number, a state abbreviation, and a specific member’s bioguide ID.

def get_members_by_state_and_district(congress, state, district, limit=2):
    bioguide_id = ''
    endpoint = f'member/congress/{congress}/{state}/{district}?api_key={API_KEY}&format=json&limit={limit}'
    response = requests.get(BASE_URL + endpoint)
    if response.status_code == 200:
        members = response.json()['members']
        for member in members:
            print(f"Name: {member['name']}")
            print(f"Party: {member['partyName']}")
            print(f"State: {member['state']}")
            print(f"District: {member['district']}")
            print(f"Bioguide ID: {member['bioguideId']}")
            bioguide_id = member['bioguideId']
            print()
    else:
        print("Failed to fetch members by state and district.")

    endpoint = f'member/{bioguide_id}/sponsored-legislation?api_key={API_KEY}&format=json&limit={limit}'
    response = requests.get(BASE_URL + endpoint)
    if response.status_code == 200:
        bills = response.json()['sponsoredLegislation']
        print("Legislation by Member:")
        for bill in bills:
            print("Sponsored")
            print(f"Title: {bill['title']}")
            print(f"Action Date: {bill['latestAction']['actionDate']}")
            print(f"Latest Action: {bill['latestAction']['text']}")
            print(f"Number: {bill['number']}")
            print()
    else:
        print("Failed to fetch legislation by member.")

    endpoint = f'member/{bioguide_id}/cosponsored-legislation?api_key={API_KEY}&format=json&limit={limit}'
    response = requests.get(BASE_URL + endpoint)
    if response.status_code == 200:
        bills = response.json()['cosponsoredLegislation']
        for bill in bills:
            print("Cosponsored")
            print(f"Title: {bill['title']}")
            print(f"Action Date: {bill['latestAction']['actionDate']}")
            print(f"Latest Action: {bill['latestAction']['text']}")
            print(f"Number: {bill['number']}")
            print()
    else:
        print("Failed to fetch cosponsored legislation by member.")
    print()

print("Members by State and District:")
# get_members_by_state_and_district('CongressNumber', 'StateCode', 'DistrictNumber', limit=num)
# Limit is optional, default is 2 with a max of 250
get_members_by_state_and_district('118', 'AL', '4')
get_members_by_state_and_district('118', 'AL', '7')
Members by State and District:
Name: Aderholt, Robert B.
Party: Republican
State: Alabama
District: 4
Bioguide ID: A000055

Legislation by Member:
Sponsored
Title: Deliver for Democracy Act
Action Date: 2024-07-22
Latest Action: Referred to the House Committee on Oversight and Accountability.
Number: 9078

Sponsored
Title: Departments of Labor, Health and Human Services, and Education, and Related Agencies Appropriations Act, 2025
Action Date: 2024-07-12
Latest Action: Placed on the Union Calendar, Calendar No. 485.
Number: 9029

Cosponsored
Title: Celebrating the principles of democracy, religious pluralism, human rights, and the rule of law shared by both the United States and India, the strong people-to-people ties between the United States and India, and the success of the Indian diaspora in the United States.
Action Date: 2024-07-30
Latest Action: Referred to the House Committee on Foreign Affairs.
Number: 1394

Cosponsored
Title: VALID Act
Action Date: 2024-04-11
Latest Action: Referred to the Subcommittee on Border Security and Enforcement.
Number: 7951


Name: Sewell, Terri A.
Party: Democratic
State: Alabama
District: 7
Bioguide ID: S001185

Legislation by Member:
Sponsored
Title: LIFT Act
Action Date: 2024-05-14
Latest Action: Referred to the House Committee on Ways and Means.
Number: 8396

Sponsored
Title: To designate the facility of the United States Postal Service located at 306 Pickens Street in Marion, Alabama, as the "Albert Turner, Sr. Post Office Building".
Action Date: 2024-06-04
Latest Action: Received in the Senate and Read twice and referred to the Committee on Homeland Security and Governmental Affairs.
Number: 7893

Cosponsored
Title: To require the Federal Communications Commission to amend the rules of the Commission to include a shark attack as an event for which a wireless emergency alert may be transmitted, and for other purposes.
Action Date: 2024-08-16
Latest Action: Referred to the House Committee on Energy and Commerce.
Number: 9376

Cosponsored
Title: SCHOOL Professionals Act of 2024
Action Date: 2024-07-25
Latest Action: Referred to the House Committee on Ways and Means.
Number: 9152