Skip to main content

CongressApiClient

Struct CongressApiClient 

Source
pub struct CongressApiClient { /* private fields */ }
Expand description

A client for interacting with the US Congress API.

Implementations§

Source§

impl CongressApiClient

Source

pub fn new(api_key: Option<String>) -> Result<Self, Box<dyn Error>>

Creates a new instance of CongressApiClient.

§Parameters
  • [api_key]: An optional API key. If None, the client will attempt to read the [CDG_API_KEY] environment variable.
§Returns
  • Ok(CongressApiClient): A new client instance.
  • Err: If the API key is not provided and not found in the environment.
Examples found in repository?
examples/bill_example.rs (line 10)
9fn main() -> Result<(), Box<dyn Error>> {
10    let client = CongressApiClient::new(None)?; // Use default API key
11
12    // Define parameters
13    let params = BillActionsParams::default()
14        .format(FormatType::Json)
15        .limit(10);
16
17    // Create the endpoint
18    let endpoint = Endpoints::BillActions(118, BillType::S, 4361, params);
19
20    // Fetch the data
21    let response: BillActionsResponse = client.fetch(endpoint)?;
22
23    // Process the response
24    for action in response.actions {
25        println!("{:#?}\n", action);
26        println!("=====================");
27        println!("=====================\n");
28    }
29
30    Ok(())
31}
More examples
Hide additional examples
examples/generic_matching.rs (line 10)
9fn main() -> Result<(), Box<dyn Error>> {
10    let client = CongressApiClient::new(None)?; // Use API key from environment
11
12    // Define parameters for bill details
13    let params = BillDetailsParams::default().format(FormatType::Json);
14
15    // Specify the bill to fetch (e.g., H.R. 1234 from the 118th Congress)
16    let endpoint = Endpoints::new_bill_details(118, BillType::Hr, 1234, params);
17
18    // Fetch the data as GenericResponse
19    let response: GenericResponse = client.fetch(endpoint)?;
20
21    // Parse the response as BillDetails
22    let bill_details: BillDetailsResponse = parse_response(&response)?;
23    let bill = bill_details.bill;
24
25    println!("Bill: {}", unwrap_option_string(bill.bill_type));
26    println!("Title: {}", unwrap_option_string(bill.title));
27    println!("Summary: {:#?}", bill.summaries.unwrap_or_default());
28
29    Ok(())
30}
examples/member_example.rs (line 10)
9fn main() -> Result<(), Box<dyn Error>> {
10    let client = CongressApiClient::new(None)?; // Use default API key
11                                                // Set the API key explicitly with:
12                                                // CongressApiClient::new(Some("api_key_here"))?;
13                                                // Define parameters
14    let params = MemberListParams::default()
15        .format(FormatType::Json)
16        .limit(10)
17        .current_member(true);
18
19    // Create the endpoint
20    let endpoint = Endpoints::MemberList(params);
21
22    // Fetch the data, casting it to the appropriate response type
23    let response: MembersResponse = client.fetch(endpoint)?;
24
25    // Process the response
26    for member in response.members {
27        println!(
28            "{}, {}, {}\n",
29            member.name.unwrap_or("".to_string()),
30            member.state.unwrap_or("".to_string()),
31            member.party_name.unwrap_or("".to_string())
32        );
33    }
34
35    Ok(())
36}
examples/daily_record.rs (line 10)
9fn main() -> Result<(), Box<dyn Error>> {
10    let client = CongressApiClient::new(None)?; // Use default API key
11
12    // Create the endpoint
13    let endpoint = Endpoints::DailyCongressionalRecordList(
14        DailyCongressionalRecordListParams::default().format(FormatType::Json),
15    );
16
17    // Fetch the data
18    let response: DailyCongressionalRecordResponse = client.fetch(endpoint)?;
19
20    // Print the data
21    for record in response.daily_congressional_record {
22        println!(
23            "Iss. Date: {}",
24            record.issue_date.unwrap_or("N/A".to_string())
25        );
26        println!(
27            "Iss. Number: {}",
28            record.issue_number.unwrap_or("N/A".to_string())
29        );
30        println!("Vol. Number: {}", record.volume_number.unwrap_or(0));
31        println!("Session: {}", record.session_number.unwrap_or(0));
32        println!("Congress: {}", record.congress.unwrap_or(0));
33        println!("URL: {}", record.url.unwrap_or("N/A".to_string()));
34        println!("\n");
35        println!("Full Issue: {:#?}", record.full_issue.unwrap_or_default());
36        println!("\n");
37        println!("=====================================");
38    }
39
40    Ok(())
41}
examples/generic_example.rs (line 12)
11fn main() -> Result<(), Box<dyn Error>> {
12    let client = CongressApiClient::new(None)?; // Use default API key
13
14    // Define parameters
15    let params = BillListParams::default().format(FormatType::Json).limit(10);
16
17    // Create the endpoint
18    let endpoint = Endpoints::BillList(params);
19
20    // Fetch the data
21    let response: GenericResponse = client.fetch(endpoint)?;
22
23    // Parse the response into a specific primary response,
24    // if it fails, it will just print the json response
25    let bill_list: BillsResponse = match parse_response(&response) {
26        Ok(bill_list) => bill_list,
27        Err(_) => {
28            println!("{}", serialize_response(&response, true)?);
29            return Ok(());
30        }
31    };
32
33    // Print the bill list
34    for bill in bill_list.bills {
35        println!("Bill: {}", unwrap_option_string(bill.bill_type));
36        println!("Title: {}", unwrap_option_string(bill.title));
37        println!("Number: {}", unwrap_option_string(bill.number));
38        println!(
39            "Origin Chamber: {}",
40            unwrap_option_string(bill.origin_chamber)
41        );
42        println!("Update Date: {}", unwrap_option_string(bill.update_date));
43        println!("URL: {}", unwrap_option_string(bill.url));
44        println!();
45    }
46
47    Ok(())
48}
examples/manual_endpoint.rs (line 12)
11fn main() -> Result<(), Box<dyn Error>> {
12    let client = CongressApiClient::new(None)?; // Use API key from environment
13
14    // Assume there's an endpoint that doesn't have a specific response model
15    let endpoint = Endpoints::new_generic(
16        "daily-congressional-record".to_string(),
17        GenericParams::default().format(FormatType::Json).limit(250),
18    );
19
20    // Fetch the data as GenericResponse
21    let response: GenericResponse = client.fetch(endpoint)?;
22
23    // Parse the response into a generic JSON value if specific parsing fails
24    match parse_response::<DailyCongressionalRecordResponse, GenericResponse>(&response) {
25        Ok(json) => {
26            json.daily_congressional_record.iter().for_each(|records| {
27                let record = records.clone();
28                println!("Date: {}", unwrap_option_string(record.issue_date));
29                println!("Update Date: {}", unwrap_option_string(record.update_date));
30                println!("Volume: {}", record.volume_number.unwrap_or_default());
31                println!("Issue: {}", unwrap_option_string(record.issue_number));
32                println!("Sess. #: {}", record.session_number.unwrap_or_default());
33                println!("Congress: {}", record.congress.unwrap_or_default());
34                println!("URL: {}", unwrap_option_string(record.url));
35                println!();
36                println!("Full Issue: {:#?}", record.full_issue.unwrap_or_default());
37            });
38        }
39        Err(e) => {
40            println!("Failed to parse response: {}", e);
41            // Serialize the response as a generic JSON value, pretty-printed = true
42            println!("{}", serialize_response(&response, true)?);
43        }
44    }
45
46    Ok(())
47}
Source

pub fn fetch<T: PrimaryResponse + DeserializeOwned>( &self, endpoint: Endpoints, ) -> Result<T, ApiClientError>

Fetches data from the US Congress API for a given endpoint.

§Parameters
§Returns
  • Result<T, ApiClientError>: The fetched data, deserialized into the appropriate response type.
§Errors
  • ApiClientError::Http: If an HTTP error occurs.
  • ApiClientError::Deserialization: If an error occurs during deserialization.
  • ApiClientError::Url: If an error occurs while building the URL.
  • ApiClientError::EnvVar: If the API key is not found in the environment.
Examples found in repository?
examples/bill_example.rs (line 21)
9fn main() -> Result<(), Box<dyn Error>> {
10    let client = CongressApiClient::new(None)?; // Use default API key
11
12    // Define parameters
13    let params = BillActionsParams::default()
14        .format(FormatType::Json)
15        .limit(10);
16
17    // Create the endpoint
18    let endpoint = Endpoints::BillActions(118, BillType::S, 4361, params);
19
20    // Fetch the data
21    let response: BillActionsResponse = client.fetch(endpoint)?;
22
23    // Process the response
24    for action in response.actions {
25        println!("{:#?}\n", action);
26        println!("=====================");
27        println!("=====================\n");
28    }
29
30    Ok(())
31}
More examples
Hide additional examples
examples/generic_matching.rs (line 19)
9fn main() -> Result<(), Box<dyn Error>> {
10    let client = CongressApiClient::new(None)?; // Use API key from environment
11
12    // Define parameters for bill details
13    let params = BillDetailsParams::default().format(FormatType::Json);
14
15    // Specify the bill to fetch (e.g., H.R. 1234 from the 118th Congress)
16    let endpoint = Endpoints::new_bill_details(118, BillType::Hr, 1234, params);
17
18    // Fetch the data as GenericResponse
19    let response: GenericResponse = client.fetch(endpoint)?;
20
21    // Parse the response as BillDetails
22    let bill_details: BillDetailsResponse = parse_response(&response)?;
23    let bill = bill_details.bill;
24
25    println!("Bill: {}", unwrap_option_string(bill.bill_type));
26    println!("Title: {}", unwrap_option_string(bill.title));
27    println!("Summary: {:#?}", bill.summaries.unwrap_or_default());
28
29    Ok(())
30}
examples/member_example.rs (line 23)
9fn main() -> Result<(), Box<dyn Error>> {
10    let client = CongressApiClient::new(None)?; // Use default API key
11                                                // Set the API key explicitly with:
12                                                // CongressApiClient::new(Some("api_key_here"))?;
13                                                // Define parameters
14    let params = MemberListParams::default()
15        .format(FormatType::Json)
16        .limit(10)
17        .current_member(true);
18
19    // Create the endpoint
20    let endpoint = Endpoints::MemberList(params);
21
22    // Fetch the data, casting it to the appropriate response type
23    let response: MembersResponse = client.fetch(endpoint)?;
24
25    // Process the response
26    for member in response.members {
27        println!(
28            "{}, {}, {}\n",
29            member.name.unwrap_or("".to_string()),
30            member.state.unwrap_or("".to_string()),
31            member.party_name.unwrap_or("".to_string())
32        );
33    }
34
35    Ok(())
36}
examples/daily_record.rs (line 18)
9fn main() -> Result<(), Box<dyn Error>> {
10    let client = CongressApiClient::new(None)?; // Use default API key
11
12    // Create the endpoint
13    let endpoint = Endpoints::DailyCongressionalRecordList(
14        DailyCongressionalRecordListParams::default().format(FormatType::Json),
15    );
16
17    // Fetch the data
18    let response: DailyCongressionalRecordResponse = client.fetch(endpoint)?;
19
20    // Print the data
21    for record in response.daily_congressional_record {
22        println!(
23            "Iss. Date: {}",
24            record.issue_date.unwrap_or("N/A".to_string())
25        );
26        println!(
27            "Iss. Number: {}",
28            record.issue_number.unwrap_or("N/A".to_string())
29        );
30        println!("Vol. Number: {}", record.volume_number.unwrap_or(0));
31        println!("Session: {}", record.session_number.unwrap_or(0));
32        println!("Congress: {}", record.congress.unwrap_or(0));
33        println!("URL: {}", record.url.unwrap_or("N/A".to_string()));
34        println!("\n");
35        println!("Full Issue: {:#?}", record.full_issue.unwrap_or_default());
36        println!("\n");
37        println!("=====================================");
38    }
39
40    Ok(())
41}
examples/generic_example.rs (line 21)
11fn main() -> Result<(), Box<dyn Error>> {
12    let client = CongressApiClient::new(None)?; // Use default API key
13
14    // Define parameters
15    let params = BillListParams::default().format(FormatType::Json).limit(10);
16
17    // Create the endpoint
18    let endpoint = Endpoints::BillList(params);
19
20    // Fetch the data
21    let response: GenericResponse = client.fetch(endpoint)?;
22
23    // Parse the response into a specific primary response,
24    // if it fails, it will just print the json response
25    let bill_list: BillsResponse = match parse_response(&response) {
26        Ok(bill_list) => bill_list,
27        Err(_) => {
28            println!("{}", serialize_response(&response, true)?);
29            return Ok(());
30        }
31    };
32
33    // Print the bill list
34    for bill in bill_list.bills {
35        println!("Bill: {}", unwrap_option_string(bill.bill_type));
36        println!("Title: {}", unwrap_option_string(bill.title));
37        println!("Number: {}", unwrap_option_string(bill.number));
38        println!(
39            "Origin Chamber: {}",
40            unwrap_option_string(bill.origin_chamber)
41        );
42        println!("Update Date: {}", unwrap_option_string(bill.update_date));
43        println!("URL: {}", unwrap_option_string(bill.url));
44        println!();
45    }
46
47    Ok(())
48}
examples/manual_endpoint.rs (line 21)
11fn main() -> Result<(), Box<dyn Error>> {
12    let client = CongressApiClient::new(None)?; // Use API key from environment
13
14    // Assume there's an endpoint that doesn't have a specific response model
15    let endpoint = Endpoints::new_generic(
16        "daily-congressional-record".to_string(),
17        GenericParams::default().format(FormatType::Json).limit(250),
18    );
19
20    // Fetch the data as GenericResponse
21    let response: GenericResponse = client.fetch(endpoint)?;
22
23    // Parse the response into a generic JSON value if specific parsing fails
24    match parse_response::<DailyCongressionalRecordResponse, GenericResponse>(&response) {
25        Ok(json) => {
26            json.daily_congressional_record.iter().for_each(|records| {
27                let record = records.clone();
28                println!("Date: {}", unwrap_option_string(record.issue_date));
29                println!("Update Date: {}", unwrap_option_string(record.update_date));
30                println!("Volume: {}", record.volume_number.unwrap_or_default());
31                println!("Issue: {}", unwrap_option_string(record.issue_number));
32                println!("Sess. #: {}", record.session_number.unwrap_or_default());
33                println!("Congress: {}", record.congress.unwrap_or_default());
34                println!("URL: {}", unwrap_option_string(record.url));
35                println!();
36                println!("Full Issue: {:#?}", record.full_issue.unwrap_or_default());
37            });
38        }
39        Err(e) => {
40            println!("Failed to parse response: {}", e);
41            // Serialize the response as a generic JSON value, pretty-printed = true
42            println!("{}", serialize_response(&response, true)?);
43        }
44    }
45
46    Ok(())
47}

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more