twitch_api_rs/
lib.rs

1// {{{ Crate level doc
2//! [![Crates.io](https://img.shields.io/crates/v/twitch-api-rs?style=plastic)](https://crates.io/crates/twitch-api-rs)
3//! [![Gihub Actions Testing CI](https://github.com/oldwomanjosiah/twitch-api.rs/workflows/Rust/badge.svg)](https://github.com/oldwomanjosiah/twitch-api.rs/actions?query=workflow%3ARust)
4//!
5//! A twitch crate used to build and send requests to
6//! the twitch helix api.
7//!
8//! See [`Twitch API Reference`]
9//!
10//! [`Twitch API Reference`]: https://dev.twitch.tv/docs/
11//!
12//! ### Example: Getting the top 20 clips from a creator
13//!
14//! To get a list of clips from the twitch api, by a streamers dislplay name, there
15//! are 4 steps.
16//!
17//! 1) Get an application ClientId and ClientSecret [^getting_credentials]
18//! 2) Request a client_flow Authentication Token
19//! 3) Use that token to request information on a user by their display name
20//! 4) Use the UserId returned by that request to request a list of clips associated
21//!     with their channel.
22//!
23//! ```
24//! # use std::env;
25//! # use std::sync::Arc;
26//! #[tokio::main]
27//! async fn main() {
28//!     use twitch_api_rs::prelude::*;
29//!     use twitch_api_rs::auth::{ClientId, ClientSecret};
30//!
31//!     // Here we use the values that you should have gotten from step one
32//!
33//!     let client_id: ClientId =
34//!         env::var("TWITCH_API_RS_TEST_CLIENT_ID")
35//!             .expect("Client Id environment variable not defined")
36//!             .into();
37//!
38//!     let client_secret: ClientSecret =
39//!         env::var("TWITCH_API_RS_TEST_CLIENT_SECRET")
40//!             .expect("Client Secret environment variable not defined")
41//!             .into();
42//!
43//!     // Make a reqwest client to send the requests, and wrap it in an arc so it
44//!     // can be reused in multiple futures
45//!     let client = Arc::new(reqwest::Client::new());
46//!
47//!     use twitch_api_rs::auth::client_credentials::{
48//!         ClientAuthRequest, ClientAuthResponse, ClientAuthToken,
49//!     };
50//!
51//!     // Step 2
52//!
53//!     // Get a client credentials (application) access token and wrap it in an arc
54//!     // to be used across multiple tasks without repeating
55//!     let auth_token: Arc<ClientAuthToken> = Arc::new(
56//!         match ClientAuthRequest::builder()
57//!             .set_client_id(client_id.clone())
58//!             .set_client_secret(client_secret)
59//!             .make_request(client.clone())
60//!             .await {
61//!                 Ok(resp) => {
62//!                     // Create the token from the token value provided by twitch and
63//!                     // your client_id
64//!                     ClientAuthToken::from_client(resp, client_id)
65//!                 }
66//!
67//!                 // Better error handling can be performed here by matching against
68//!                 // the type of this requests::RequestError. Elided for conciseness
69//!                 Err(e) => panic!("Could not complete auth request for reason {}", e),
70//!             }
71//!     );
72//!
73//!     // Step 3
74//!
75//!     use twitch_api_rs::values::users::UserId;
76//!     use twitch_api_rs::resource::users::get_users::*;
77//!
78//!     // Notice that we get a Vec<UserId> here, as this endpoint allows you to query
79//!     // for multiple users at once
80//!     let user_ids: Vec<UserId> =
81//!         match GetUsersRequest::builder()
82//!             .set_auth(auth_token.clone())
83//!             .add_login("TheHoodlum12")
84//!             .make_request(client.clone())
85//!             .await {
86//!                 Ok(mut resp) => {
87//!                     resp.users.into_iter().map(|i| i.id).collect()
88//!                 }
89//!
90//!                 Err(e) =>
91//!                     panic!("Could not complete request for user by display name for reason {}", e),
92//!             };
93//!
94//!     // Step 4
95//!
96//!     use twitch_api_rs::resource::clips::ClipInfo;
97//!     use twitch_api_rs::resource::clips::get_clips::*;
98//!     use twitch_api_rs::values::clips::ClipTitle;
99//!
100//!     for user_id in user_ids {
101//!         let auth_token = auth_token.clone();
102//!         let client = client.clone();
103//!
104//!         tokio::spawn(async move {
105//!             match GetClipsRequest::builder()
106//!                 .set_auth(auth_token)
107//!                 .set_broadcaster_id(user_id.clone())
108//!                 .make_request(client)
109//!                 .await {
110//!                     Ok(resp) => {
111//!                         // Print out the response
112//!                         for clip in resp.clips {
113//!                             eprintln!(
114//!                                 "Found clip for broadcaster {:?} titled {:?}",
115//!                                 &user_id, clip.title
116//!                             );
117//!                         }
118//!                     }
119//!                     Err(e) =>
120//!                         panic!("Could not get clips for user {:?} for reason {}", user_id, e),
121//!                 }
122//!         });
123//!     }
124//! }
125//! ```
126//!
127//! [^getting_credentials]: If you do not already have these then you will need to
128//!     log into your [`twitch developer console`], create and name a new application, and copy down
129//!     the associated values.  
130//!     The client secret that you get from this process is imediately invalidated if you request a
131//!     new one, and it will not be shown to you once you leave the page where you generate it, so
132//!     make sure to write it down somewhere safe. It is recommended that you treat it like a
133//!     password.
134//!
135//! [`twitch developer console`]: https://dev.twitch.tv/console
136// }}}
137#![deny(missing_docs, missing_debug_implementations)]
138#![cfg_attr(feature = "nightly", feature(doc_spotlight))]
139
140pub mod auth;
141pub mod requests;
142pub mod resource;
143pub mod values;
144
145/// Common functions and types used in most application
146pub mod prelude {
147    /// Trait used by many endpoints for authentication and scopes
148    pub use crate::auth::AuthToken;
149
150    /// Trait that exposes methods common to all requests, required to use
151    /// `.make_request(&client).await`
152    pub use crate::requests::Request;
153
154    /// Types produced and consumed by endpoints
155    pub use crate::values;
156}
157
158mod crate_prelude {
159    pub use crate::auth::{self, AuthToken};
160    pub use crate::requests::*;
161    pub use reqwest::Method;
162
163    pub mod serde_derive {
164        pub use serde::{Deserialize, Serialize};
165    }
166    pub mod serde_impl {
167        pub use serde::{ser::SerializeMap, Deserialize, Serialize, Serializer};
168    }
169}