Maintainers
Pricing
Enterprise
More
More
Documentation
Try Live
Rankings
Install
Blog
Docs7
Ask
New
Add Docs
Ferinth
https://docs.rs/ferinth/
Admin
Ferinth is a Rust library providing asynchronous API bindings for the Modrinth API.
Tokens:
42,887
Snippets:
404
Trust Score:
9.1
Update:
1 month ago
Context
Chat
Benchmark
Latest
Show doc for...
Code
Info
Show Results
Tokens:
Raw
Copy
Link
Tokens:
Raw
Copy
Link
### GET /tag/game_version Source: https://docs.rs/ferinth/latest/src/ferinth/api_calls/tag.rs.html List the game versions and information about them. ```APIDOC ## GET /tag/game_version ### Description List the game versions and information about them. ### Method GET ### Endpoint /tag/game_version ``` -------------------------------- ### FromIterator Implementation Examples Source: https://docs.rs/ferinth/latest/ferinth/type.Result.html Demonstrates collecting Results into a container, showing how the process stops at the first Err. ```rust let v = vec![1, 2]; let res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32| x.checked_add(1).ok_or("Overflow!") ).collect(); assert_eq!(res, Ok(vec![2, 3])); ``` ```rust let v = vec![1, 2, 0]; let res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32| x.checked_sub(1).ok_or("Underflow!") ).collect(); assert_eq!(res, Err("Underflow!")); ``` ```rust let v = vec![3, 2, 1, 10]; let mut shared = 0; let res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32| { shared += x; x.checked_sub(2).ok_or("Underflow!") }).collect(); assert_eq!(res, Err("Underflow!")); assert_eq!(shared, 6); ``` -------------------------------- ### Unwrap or Else Example Source: https://docs.rs/ferinth/latest/ferinth/type.Result.html Demonstrates using unwrap_or_else to provide a fallback value. ```rust assert_eq!(Ok(2).unwrap_or_else(count), 2); assert_eq!(Err("foo").unwrap_or_else(count), 3); ``` -------------------------------- ### GET /tag/project_type Source: https://docs.rs/ferinth/latest/src/ferinth/api_calls/tag.rs.html List valid project types. ```APIDOC ## GET /tag/project_type ### Description List valid project types. ### Method GET ### Endpoint /tag/project_type ``` -------------------------------- ### GET /tag/license/{id} Source: https://docs.rs/ferinth/latest/src/ferinth/api_calls/tag.rs.html Get the text and title of a license. ```APIDOC ## GET /tag/license/{id} ### Description Get the text and title of a license. ### Method GET ### Endpoint /tag/license/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The license ID ``` -------------------------------- ### Create DateTime from seconds Source: https://docs.rs/ferinth/latest/ferinth/structures/type.UtcTime.html Examples of creating UTC datetimes from Unix timestamps using Option::and_then and Iterator::map. ```rust let maybe_timestamp: Option<i64> = Some(1431648000); let maybe_dt = maybe_timestamp.and_then(DateTime::from_timestamp_secs); assert!(maybe_dt.is_some()); assert_eq!(maybe_dt.unwrap().to_string(), "2015-05-15 00:00:00 UTC"); ``` ```rust let v = vec![i64::MIN, 1_000_000_000, 1_234_567_890, i64::MAX]; let timestamps: Vec<Option<DateTime<Utc>>> = v .into_iter() .map(DateTime::from_timestamp_secs) .collect(); assert_eq!(vec![ None, Some(DateTime::parse_from_rfc3339("2001-09-09 01:46:40Z").unwrap().to_utc()), Some(DateTime::parse_from_rfc3339("2009-02-13 23:31:30Z").unwrap().to_utc()), None, ], timestamps); ``` -------------------------------- ### Get license details Source: https://docs.rs/ferinth/latest/src/ferinth/api_calls/tag.rs.html Retrieves the text and title of a specific license by its ID. ```rust # tokio_test::block_on(async { # let modrinth = ferinth::Ferinth::default(); let license = modrinth.tag_license_text_and_title("MIT").await?; assert_eq!(license.title, "MIT License"); assert!(license.body.contains("MIT License")); # Ok::<_, ferinth::Error>(()) }).unwrap() ``` -------------------------------- ### Get Version by Number Source: https://docs.rs/ferinth/latest/src/ferinth/api_calls/version.rs.html Retrieves a version by its version number string associated with a specific project ID. ```rust # tokio_test::block_on(async { # let modrinth = ferinth::Ferinth::default(); let version = modrinth.version_get_from_number("sodium", "mc1.17.1-0.3.2").await?; assert_eq!(version.id, "xuWxRZPd"); # Ok::<_, ferinth::Error>(()) }).unwrap() ``` ```rust pub async fn version_get_from_number(&self, project_id: &str, number: &str) -> Result<Version> { check_id_slug(&[project_id])?; self.client .get(API_BASE_URL.join_all(vec!["project", project_id, "version", number])) .custom_send_json() .await } ``` -------------------------------- ### Get a specific version Source: https://docs.rs/ferinth/latest/src/ferinth/api_calls/version.rs.html Retrieves details for a single version by its ID. ```rust # tokio_test::block_on(async { # let modrinth = ferinth::Ferinth::default(); let sodium_version = modrinth.version_get("xuWxRZPd").await?; assert_eq!(sodium_version.project_id, "AANobbMI"); # Ok::<_, ferinth::Error>(()) }).unwrap() ``` -------------------------------- ### GET /tag/category Source: https://docs.rs/ferinth/latest/src/ferinth/api_calls/tag.rs.html List the categories, their icons, and applicable project types. ```APIDOC ## GET /tag/category ### Description List the categories, their icons, and applicable project types. ### Method GET ### Endpoint /tag/category ``` -------------------------------- ### Get project versions Source: https://docs.rs/ferinth/latest/src/ferinth/api_calls/version.rs.html Retrieves a list of all versions associated with a specific project ID. ```rust # tokio_test::block_on(async { # let modrinth = ferinth::Ferinth::default(); let sodium_versions = modrinth.version_list("AANobbMI").await?; sodium_versions.iter().for_each(|v| assert_eq!(v.project_id, "AANobbMI")); # Ok::<_, ferinth::Error>(()) }).unwrap() ``` -------------------------------- ### GET /tag/loader Source: https://docs.rs/ferinth/latest/src/ferinth/api_calls/tag.rs.html List the loaders, their icons, and supported project types. ```APIDOC ## GET /tag/loader ### Description List the loaders, their icons, and supported project types. ### Method GET ### Endpoint /tag/loader ``` -------------------------------- ### Get Multiple Versions Source: https://docs.rs/ferinth/latest/src/ferinth/api_calls/version.rs.html Retrieves a list of versions based on a slice of version IDs. ```rust # tokio_test::block_on(async { # let modrinth = ferinth::Ferinth::default(); let versions = modrinth.version_get_multiple(&[ "sxWTUZpD", "mgPpe4NY", ]).await?; versions.iter().for_each(|v| assert_eq!(v.project_id, "of7wIinq")); # Ok::<_, ferinth::Error>(()) }).unwrap() ``` ```rust pub async fn version_get_multiple(&self, version_ids: &[&str]) -> Result<Vec<Version>> { check_id_slug(version_ids)?; self.client .get( API_BASE_URL .join_all(vec!["versions"]) .with_query_json("ids", version_ids)?, ) .custom_send_json() .await } ``` -------------------------------- ### Get a project by ID or slug Source: https://docs.rs/ferinth/latest/src/ferinth/api_calls/project.rs.html Retrieves a single project using its unique ID or case-insensitive slug. ```rust # tokio_test::block_on(async { # let modrinth = ferinth::Ferinth::default(); // Get a mod using its project ID let sodium = modrinth.project_get("AANobbMI").await?; assert_eq!(sodium.title, "Sodium"); // You can also use the project's slug, which is case-insensitive let ok_zoomer = modrinth.project_get("fAbRiC-aPi").await?; assert_eq!(ok_zoomer.title, "Fabric API"); # Ok::<_, ferinth::Error>(()) }).unwrap() ``` -------------------------------- ### Get multiple projects Source: https://docs.rs/ferinth/latest/src/ferinth/api_calls/project.rs.html Retrieves a list of projects using a slice of IDs or slugs. ```rust # tokio_test::block_on(async { # let modrinth = ferinth::Ferinth::default(); // You can use both IDs and slugs let projects = modrinth.project_get_multiple(&[ "sodium", "P7dR8mSH", "iris", "gvQqBUqZ", ]).await?; assert_eq!(projects.len(), 4); # Ok::<_, ferinth::Error>(()) }).unwrap() ``` -------------------------------- ### IntoIterator Implementation Examples Source: https://docs.rs/ferinth/latest/ferinth/type.Result.html Demonstrates converting a Result into an iterator that yields the contained value if Ok, or nothing if Err. ```rust let x: Result<u32, &str> = Ok(5); let v: Vec<u32> = x.into_iter().collect(); assert_eq!(v, [5]); let x: Result<u32, &str> = Err("nothing!"); let v: Vec<u32> = x.into_iter().collect(); assert_eq!(v, []); ``` -------------------------------- ### Get multiple users Source: https://docs.rs/ferinth/latest/src/ferinth/api_calls/user.rs.html Retrieves information for a list of users by their IDs. ```rust # use ferinth::structures::user::UserRole; # tokio_test::block_on(async { # let modrinth = ferinth::Ferinth::default(); let users = modrinth.user_get_multiple(&["TEZXhE2U", "7Azq6eD8"]).await?; assert_eq!(users.len(), 2); # Ok::<_, ferinth::Error>(()) }).unwrap() ``` -------------------------------- ### Get instance statistics Source: https://docs.rs/ferinth/latest/src/ferinth/api_calls/misc.rs.html Retrieves general statistics about the Modrinth instance. ```rust # tokio_test::block_on(async { # let modrinth = ferinth::Ferinth::default(); let statistics = modrinth.instance_statistics().await?; # Ok::<_, ferinth::Error>(()) }).unwrap() ``` -------------------------------- ### Copying Result Contents Source: https://docs.rs/ferinth/latest/ferinth/type.Result.html Examples of using the copied method to copy the contents of an Ok variant. ```rust let val = 12; let x: Result<&i32, i32> = Ok(&val); assert_eq!(x, Ok(&12)); let copied = x.copied(); assert_eq!(copied, Ok(12)); ``` ```rust let mut val = 12; let x: Result<&mut i32, i32> = Ok(&mut val); assert_eq!(x, Ok(&mut 12)); let copied = x.copied(); assert_eq!(copied, Ok(12)); ``` -------------------------------- ### Get a single user Source: https://docs.rs/ferinth/latest/src/ferinth/api_calls/user.rs.html Retrieves information for a specific user by their ID. ```rust # tokio_test::block_on(async { # let modrinth = ferinth::Ferinth::default(); let theRookieCoder = modrinth.user_get("7Azq6eD8").await?; assert_eq!( theRookieCoder.role, ferinth::structures::user::UserRole::Developer, ); # Ok::<_, ferinth::Error>(()) }).unwrap() ``` -------------------------------- ### Get Version by ID Source: https://docs.rs/ferinth/latest/src/ferinth/api_calls/version.rs.html Retrieves a specific version using its unique version ID. ```rust pub async fn version_get(&self, version_id: &str) -> Result<Version> { check_id_slug(&[version_id])?; self.client .get(API_BASE_URL.join_all(vec!["version", version_id])) .custom_send_json() .await } ``` -------------------------------- ### Cloning Result Contents Source: https://docs.rs/ferinth/latest/ferinth/type.Result.html Examples of using the cloned method to clone the contents of an Ok variant. ```rust let val = 12; let x: Result<&i32, i32> = Ok(&val); assert_eq!(x, Ok(&12)); let cloned = x.cloned(); assert_eq!(cloned, Ok(12)); ``` ```rust let mut val = 12; let x: Result<&mut i32, i32> = Ok(&mut val); assert_eq!(x, Ok(&mut 12)); let cloned = x.cloned(); assert_eq!(cloned, Ok(12)); ``` -------------------------------- ### Flattening Nested Results Source: https://docs.rs/ferinth/latest/ferinth/type.Result.html Examples of flattening nested Result types. ```rust let x: Result<Result<&'static str, u32>, u32> = Ok(Ok("hello")); assert_eq!(Ok("hello"), x.flatten()); let x: Result<Result<&'static str, u32>, u32> = Ok(Err(6)); assert_eq!(Err(6), x.flatten()); let x: Result<Result<&'static str, u32>, u32> = Err(6); assert_eq!(Err(6), x.flatten()); ``` ```rust let x: Result<Result<Result<&'static str, u32>, u32>, u32> = Ok(Ok(Ok("hello"))); assert_eq!(Ok(Ok("hello")), x.flatten()); assert_eq!(Ok("hello"), x.flatten().flatten()); ``` -------------------------------- ### Get filtered project versions Source: https://docs.rs/ferinth/latest/src/ferinth/api_calls/version.rs.html Retrieves versions for a project, filtered by loaders, game versions, or featured status. ```rust # tokio_test::block_on(async { # let modrinth = ferinth::Ferinth::default(); let sodium_forge_versions = modrinth.version_list_filtered( "AANobbMI", Some(&["forge"]), None, None ).await?; // Sodium is not made for Forge assert!(sodium_forge_versions.is_empty()); # Ok::<_, ferinth::Error>(()) }).unwrap() ``` -------------------------------- ### Conditional Result Inspection Source: https://docs.rs/ferinth/latest/ferinth/type.Result.html Example of using is_ok_and to check if a result is Ok and matches a predicate. ```rust let x: Result<u32, &str> = Ok(2); assert_eq!(x.is_ok_and(|x| x > 1), true); let x: Result<u32, &str> = Ok(0); assert_eq!(x.is_ok_and(|x| x > 1), false); let x: Result<u32, &str> = Err("hey"); assert_eq!(x.is_ok_and(|x| x > 1), false); let x: Result<String, &str> = Ok("ownership".to_string()); assert_eq!(x.as_ref().is_ok_and(|x| x.len() > 1), true); println!("still alive {:?}", x); ``` -------------------------------- ### Unwrap Unchecked Examples Source: https://docs.rs/ferinth/latest/ferinth/type.Result.html Demonstrates the use of unwrap_unchecked, which is unsafe and causes undefined behavior if called on an Err variant. ```rust let x: Result<u32, &str> = Ok(2); assert_eq!(unsafe { x.unwrap_unchecked() }, 2); ``` ```rust let x: Result<u32, &str> = Err("emergency failure"); unsafe { x.unwrap_unchecked() }; // Undefined behavior! ``` -------------------------------- ### Concatenate Strings Source: https://docs.rs/ferinth/latest/ferinth/structures/type.ID.html Examples of concatenating strings using the + operator, including handling ownership and cloning. ```rust let a = String::from("hello"); let b = String::from(" world"); let c = a + &b; // `a` is moved and can no longer be used here. ``` ```rust let a = String::from("hello"); let b = String::from(" world"); let c = a.clone() + &b; // `a` is still valid here. ``` ```rust let a = "hello"; let b = " world"; let c = a.to_string() + b; ``` -------------------------------- ### Get and convert UNIX timestamp Source: https://docs.rs/ferinth/latest/ferinth/structures/type.UtcTime.html Retrieve the UNIX timestamp as seconds since epoch and demonstrate the reverse conversion. ```rust use chrono::{DateTime, TimeZone, Utc}; let dt: DateTime<Utc> = Utc.with_ymd_and_hms(2015, 5, 15, 0, 0, 0).unwrap(); assert_eq!(dt.timestamp(), 1431648000); assert_eq!(DateTime::from_timestamp(dt.timestamp(), dt.timestamp_subsec_nanos()).unwrap(), dt); ``` -------------------------------- ### Unwrap Err Unchecked Examples Source: https://docs.rs/ferinth/latest/ferinth/type.Result.html Demonstrates the use of unwrap_err_unchecked, which is unsafe and causes undefined behavior if called on an Ok variant. ```rust let x: Result<u32, &str> = Ok(2); unsafe { x.unwrap_err_unchecked() }; // Undefined behavior! ``` ```rust let x: Result<u32, &str> = Err("emergency failure"); assert_eq!(unsafe { x.unwrap_err_unchecked() }, "emergency failure"); ``` -------------------------------- ### Manage Project Gallery and Icons Source: https://docs.rs/ferinth/latest/src/ferinth/api_calls/project.rs.html Demonstrates adding gallery images and updating project icons using the Ferinth client. Requires an authenticated client instance and a valid project ID. ```rust 427 &project::ImageFileExt::PNG, 428 true, 429 Some("Test image, do not delete".to_string()), 430 Some(chrono::offset::Local::now().to_string()), 431 ) 432 .await?; 433 let project = modrinth.project_get(project_id).await?; 434 assert_eq!( 435 project.gallery[0].title, 436 Some("Test image, do not delete".into()) 437 ); 438 439 Ok(()) 440 } ``` ```rust #[tokio::test] 443 async fn project_icon() -> Result<()> { 444 let modrinth = Ferinth::<Authenticated>::new( 445 env!("CARGO_CRATE_NAME"), 446 Some(env!("CARGO_PKG_VERSION")), 447 None, 448 env!("MODRINTH_TOKEN"), 449 )?; 450 let project_id = env!("TEST_PROJECT_ID"); 451 452 modrinth.project_delete_icon(project_id).await?; 453 let project = modrinth.project_get(project_id).await?; 454 assert!(project.icon_url.is_none()); 455 456 let image = std::fs::read("test_image.png").expect("Cannot read test image"); 457 modrinth 458 .project_edit_icon(project_id, image, project::ImageFileExt::PNG) 459 .await?; 460 let project = modrinth.project_get(project_id).await?; 461 assert!(project.icon_url.is_some()); 462 463 Ok(()) 464 } 465} ``` -------------------------------- ### GET /tag/side_type Source: https://docs.rs/ferinth/latest/src/ferinth/api_calls/tag.rs.html List valid side types. ```APIDOC ## GET /tag/side_type ### Description List valid side types. ### Method GET ### Endpoint /tag/side_type ``` -------------------------------- ### Initialize Ferinth Client with Authorization Source: https://docs.rs/ferinth/latest/src/ferinth/lib.rs.html Configures the client builder with default authorization headers using a provided token. ```rust Ok(Self { auth: PhantomData, client: Self::client_builder(name, version, contact) .default_headers(HeaderMap::from_iter([ (reqwest::header::AUTHORIZATION, token.try_into()?), ])) .build() .expect("Failed to initialise TLS backend"), }) } } ``` -------------------------------- ### GET /tag/report_type Source: https://docs.rs/ferinth/latest/src/ferinth/api_calls/tag.rs.html List valid report types. ```APIDOC ## GET /tag/report_type ### Description List valid report types. ### Method GET ### Endpoint /tag/report_type ``` -------------------------------- ### Define Welcome structure Source: https://docs.rs/ferinth/latest/src/ferinth/structures/misc.rs.html Represents the welcome message and metadata returned by the API. ```rust #[derive(Deserialize, Serialize, Debug, Clone)] pub struct Welcome { pub about: String, pub documentation: Url, pub name: String, pub version: String, } ``` -------------------------------- ### GET /tag/donation_platform Source: https://docs.rs/ferinth/latest/src/ferinth/api_calls/tag.rs.html List donation platforms and information about them. ```APIDOC ## GET /tag/donation_platform ### Description List donation platforms and information about them. ### Method GET ### Endpoint /tag/donation_platform ``` -------------------------------- ### Create new String Source: https://docs.rs/ferinth/latest/ferinth/structures/type.ID.html Creates a new empty String. ```rust let s = String::new(); ``` -------------------------------- ### Initialize Ferinth Container Source: https://docs.rs/ferinth/latest/ferinth/struct.Ferinth.html Methods for creating a new Ferinth instance, either using default settings or custom configuration. ```rust let modrinth = ferinth::Ferinth::default(); ``` ```rust let modrinth = ferinth::Ferinth::new( env!("CARGO_CRATE_NAME"), Some(env!("CARGO_PKG_VERSION")), Some("contact@program.com"), args.modrinth_token.as_ref(), )?; ``` -------------------------------- ### Ferinth::new (Authenticated) Source: https://docs.rs/ferinth/latest/src/ferinth/lib.rs.html Initializes the Ferinth client with custom user agent details and an authentication token. ```APIDOC ## Ferinth::new(name, version, contact, token) ### Description Instantiates the container with provided user agent details and an authentication token. Fails if the provided token cannot be converted into a HeaderValue. ### Parameters - **name** (&str) - Required - The name of the program. - **version** (Option<&str>) - Optional - The version of the program. - **contact** (Option<&str>) - Optional - Contact information for the program. - **token** (V) - Required - The authentication token. ``` -------------------------------- ### Welcome Struct Definition Source: https://docs.rs/ferinth/latest/ferinth/structures/misc/struct.Welcome.html The structure definition for the Welcome type, containing basic project information fields. ```rust pub struct Welcome { pub about: String, pub documentation: Url, pub name: String, pub version: String, } ``` -------------------------------- ### Ferinth::new (Unauthenticated) Source: https://docs.rs/ferinth/latest/src/ferinth/lib.rs.html Initializes the Ferinth client with custom user agent details. ```APIDOC ## Ferinth::new(name, version, contact) ### Description Instantiates the container with provided user agent details. The program name is required; version and contact are optional but recommended. ### Parameters - **name** (&str) - Required - The name of the program. - **version** (Option<&str>) - Optional - The version of the program. - **contact** (Option<&str>) - Optional - Contact information for the program. ``` -------------------------------- ### Define Version and VersionFile structures Source: https://docs.rs/ferinth/latest/src/ferinth/structures/version.rs.html Core structures for representing a project version and its associated files. ```rust #[derive(Deserialize, Serialize, Debug, Clone)] pub struct Version { pub name: String, /// Ideally will follow semantic versioning pub version_number: String, pub changelog: Option<String>, pub dependencies: Vec<Dependency>, pub game_versions: Vec<String>, /// The release channel for this version pub version_type: VersionType, pub loaders: Vec<String>, pub featured: bool, pub status: Option<Status>, pub requested_status: Option<RequestedStatus>, pub id: ID, pub project_id: ID, /// The user ID of the author who published this version pub author_id: ID, pub date_published: UtcTime, pub downloads: Int, /// A list of files available for download pub files: Vec<VersionFile>, } #[derive(Deserialize, Serialize, Debug, Clone)] pub struct VersionFile { pub hashes: Hash, pub url: Url, pub filename: String, /// Whether the file is the primary file of its version /// /// There can only be a maximum of one primary file per version. /// If there are no primary files specified, the first file can be taken as the primary one. pub primary: bool, /// The size of the file in bytes pub size: Int, /// The type of the additional file, used mainly for adding resource packs to datapacks pub file_type: Option<AdditionalFileType>, } ``` -------------------------------- ### Checking Result Status Source: https://docs.rs/ferinth/latest/ferinth/type.Result.html Examples of checking if a result is Ok or Err. ```rust let x: Result<i32, &str> = Ok(-3); assert_eq!(x.is_ok(), true); let x: Result<i32, &str> = Err("Some error message"); assert_eq!(x.is_ok(), false); ``` ```rust let x: Result<i32, &str> = Ok(-3); assert_eq!(x.is_err(), false); let x: Result<i32, &str> = Err("Some error message"); assert_eq!(x.is_err(), true); ``` -------------------------------- ### Search for projects Source: https://docs.rs/ferinth/latest/src/ferinth/api_calls/search.rs.html Use search to perform a standard project query with sorting and facet filtering. ```rust # use ferinth::structures::search::{Sort, Facet}; # tokio_test::block_on(async { # let modrinth = ferinth::Ferinth::default(); // When searching for 'sodium' and filtering by NeoForge mods let results = modrinth.search( "sodium", &Sort::Downloads, vec![vec![ Facet::Categories("neoforge".into()) ]], ).await?; // Sodium should be the result with the most downloads assert_eq!(results.hits[0].slug, Some("sodium".to_owned())); # Ok::<_, ferinth::Error>(()) }).unwrap() ``` -------------------------------- ### Transposing Result Source: https://docs.rs/ferinth/latest/ferinth/type.Result.html Example of transposing a Result of an Option into an Option of a Result. ```rust #[derive(Debug, Eq, PartialEq)] struct SomeErr; let x: Result<Option<i32>, SomeErr> = Ok(Some(5)); let y: Option<Result<i32, SomeErr>> = Some(Ok(5)); assert_eq!(x.transpose(), y); ``` -------------------------------- ### Retrieve User Information Source: https://docs.rs/ferinth/latest/ferinth/struct.Ferinth.html Methods to fetch user profiles and their associated projects. ```rust let theRookieCoder = modrinth.user_get("7Azq6eD8").await?; assert_eq!( theRookieCoder.role, ferinth::structures::user::UserRole::Developer, ); ``` ```rust let users = modrinth.user_get_multiple(&["TEZXhE2U", "7Azq6eD8"]).await?; assert_eq!(users.len(), 2); ``` ```rust let jellysquid_projects = modrinth.user_list_projects("TEZXhE2U").await?; assert_eq!(jellysquid_projects.len(), 4); ``` -------------------------------- ### Recreate DateTime from components Source: https://docs.rs/ferinth/latest/ferinth/structures/type.UtcTime.html Demonstrates how to extract components from a DateTime and reconstruct it using from_naive_utc_and_offset. ```rust use chrono::{DateTime, Local}; let dt = Local::now(); // Get components let naive_utc = dt.naive_utc(); let offset = dt.offset().clone(); // Serialize, pass through FFI... and recreate the `DateTime`: let dt_new = DateTime::<Local>::from_naive_utc_and_offset(naive_utc, offset); assert_eq!(dt, dt_new); ``` -------------------------------- ### Convert Cow<'a, str> to String Source: https://docs.rs/ferinth/latest/ferinth/structures/type.ID.html Shows how to convert a clone-on-write string into an owned String, which may involve heap allocation. ```rust // If the string is not owned... let cow: Cow<'_, str> = Cow::Borrowed("eggplant"); // It will allocate on the heap and copy the string. let owned: String = String::from(cow); assert_eq!(&owned[..], "eggplant"); ``` -------------------------------- ### Get current user Source: https://docs.rs/ferinth/latest/ferinth/struct.Ferinth.html Retrieves the user profile associated with the current authorization header. ```rust let current_user = modrinth.user_get_current().await?; // The email should be visible as we are authorised assert!(current_user.email.is_some()); ``` -------------------------------- ### Ferinth::default Source: https://docs.rs/ferinth/latest/src/ferinth/lib.rs.html Initializes the Ferinth client with a default user agent based on the crate name and version, without authentication. ```APIDOC ## Ferinth::default() ### Description Initializes the Ferinth client with a default user agent based on the crate name and version. This instance does not have authentication configured. ### Usage ```rust let modrinth = ferinth::Ferinth::default(); ``` ``` -------------------------------- ### Retrieve Project Dependencies Source: https://docs.rs/ferinth/latest/ferinth/struct.Ferinth.html Fetches the dependencies for a given project. ```rust let fabric_api = modrinth.project_get_dependencies("fabric-api").await?; // Fabric API should not have any dependencies assert!(fabric_api.projects.is_empty()); ``` -------------------------------- ### List project types Source: https://docs.rs/ferinth/latest/src/ferinth/api_calls/tag.rs.html Retrieves a list of valid project types. ```rust # tokio_test::block_on(async { # let modrinth = ferinth::Ferinth::default(); let report_types = modrinth.tag_list_project_types().await?; # Ok::<_, ferinth::Error>(()) }).unwrap() ``` -------------------------------- ### Test Project Follow and Unfollow Source: https://docs.rs/ferinth/latest/src/ferinth/api_calls/project.rs.html A test case demonstrating how to follow and unfollow a project, verifying the state by listing followed projects. ```rust #[tokio::test] async fn follow() -> Result<()> { let modrinth = Ferinth::<Authenticated>::new( env!("CARGO_CRATE_NAME"), Some(env!("CARGO_PKG_VERSION")), None, env!("MODRINTH_TOKEN"), )?; let project_id = env!("TEST_PROJECT_ID"); let user_id = modrinth.user_get_current().await?.id; match modrinth.project_follow(project_id).await { Ok(_) => {} Err(Error::ReqwestError(e)) => { if !(e.is_status() && e.status().unwrap() == 400) { return Err(Error::ReqwestError(e)); } } Err(e) => return Err(e), } let followed_projects = modrinth.user_list_followed_projects(&user_id).await?; assert!(followed_projects .iter() .map(|p| &p.id) .any(|id| id == project_id)); modrinth.project_unfollow(project_id).await?; let followed_projects = modrinth.user_list_followed_projects(&user_id).await?; assert!(followed_projects .iter() .map(|p| &p.id) .all(|id| id != project_id)); Ok(()) } ``` -------------------------------- ### List game versions Source: https://docs.rs/ferinth/latest/src/ferinth/api_calls/tag.rs.html Retrieves a list of game versions and information about them. ```rust # tokio_test::block_on(async { # let modrinth = ferinth::Ferinth::default(); let game_versions = modrinth.tag_list_game_versions().await?; # Ok::<_, ferinth::Error>(()) }).unwrap() ``` -------------------------------- ### Retrieve Project Information Source: https://docs.rs/ferinth/latest/ferinth/struct.Ferinth.html Methods for fetching single or multiple projects by ID or slug. ```rust // Get a mod using its project ID let sodium = modrinth.project_get("AANobbMI").await?; assert_eq!(sodium.title, "Sodium"); // You can also use the project's slug, which is case-insensitive let ok_zoomer = modrinth.project_get("fAbRiC-aPi").await?; assert_eq!(ok_zoomer.title, "Fabric API"); ``` ```rust // You can use both IDs and slugs let projects = modrinth.project_get_multiple(&[ "sodium", "P7dR8mSH", "iris", "gvQqBUqZ", ]).await?; assert_eq!(projects.len(), 4); ``` -------------------------------- ### Get String length Source: https://docs.rs/ferinth/latest/ferinth/structures/type.ID.html Returns the length of the string in bytes. Note that this may differ from the number of characters or graphemes. ```rust let a = String::from("foo"); assert_eq!(a.len(), 3); let fancy_f = String::from("ƒoo"); assert_eq!(fancy_f.len(), 4); assert_eq!(fancy_f.chars().count(), 3); ``` -------------------------------- ### Retrieve multiple versions by hashes Source: https://docs.rs/ferinth/latest/ferinth/struct.Ferinth.html Fetches a map of versions corresponding to a list of SHA1 hashes. ```rust let sodium_hash = "795d4c12bffdb1b21eed5ff87c07ce5ca3c0dcbf"; let snwylvspls_hash = "994ee99d172a5950a51ec2d08c158d270722d871"; let versions = modrinth.version_get_from_multiple_hashes(vec![ sodium_hash.into(), snwylvspls_hash.into(), ]).await?; assert_eq!(versions[sodium_hash].project_id, "AANobbMI"); assert_eq!(versions[snwylvspls_hash].project_id, "of7wIinq"); ``` -------------------------------- ### List user projects Source: https://docs.rs/ferinth/latest/src/ferinth/api_calls/user.rs.html Retrieves a list of projects owned by a specific user. ```rust # tokio_test::block_on(async { # let modrinth = ferinth::Ferinth::default(); let jellysquid_projects = modrinth.user_list_projects("TEZXhE2U").await?; assert_eq!(jellysquid_projects.len(), 4); # Ok::<_, ferinth::Error>(()) }).unwrap() ``` -------------------------------- ### Calculate product of Result elements Source: https://docs.rs/ferinth/latest/ferinth/type.Result.html Demonstrates using the product method to multiply numbers parsed from strings, returning an error if parsing fails. ```rust let nums = vec!["5", "10", "1", "2"]; let total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product(); assert_eq!(total, Ok(100)); let nums = vec!["5", "10", "one", "2"]; let total: Result<usize, _> = nums.iter().map(|w| w.parse::<usize>()).product(); assert!(total.is_err()); ``` -------------------------------- ### Test Project Gallery Management Source: https://docs.rs/ferinth/latest/src/ferinth/api_calls/project.rs.html A test case demonstrating editing and deleting images from a project's gallery. ```rust #[tokio::test] async fn gallery() -> Result<()> { let modrinth = Ferinth::<Authenticated>::new( env!("CARGO_CRATE_NAME"), Some(env!("CARGO_PKG_VERSION")), None, env!("MODRINTH_TOKEN"), )?; let project_id = env!("TEST_PROJECT_ID"); let project = modrinth.project_get(project_id).await?; if !project.gallery.is_empty() { assert_ne!(project.gallery[0].title, Some("Modified test image".into())); modrinth .project_edit_gallery_image( project_id, project.gallery[0].url.clone(), Some(false), Some("Modified test image"), None, None, ) .await?; let project = modrinth.project_get(project_id).await?; assert_eq!(project.gallery[0].title, Some("Modified test image".into())); assert!(!project.gallery[0].featured); modrinth .project_delete_gallery_image(project_id, project.gallery[0].url.clone()) .await?; let project = modrinth.project_get(project_id).await?; assert!(project.gallery.is_empty()); } let image_data = std::fs::read("test_image.png").expect("Failed to read test image"); modrinth .project_add_gallery_image( project_id, image_data, ``` -------------------------------- ### new (Unauthenticated) Source: https://docs.rs/ferinth/latest/ferinth/struct.Ferinth.html Instantiates a new Ferinth client without authentication. ```APIDOC ## pub fn new(name: &str, version: Option<&str>, contact: Option<&str>) -> Self ### Description Instantiate the container with the provided user agent details. The program name is required; version and contact are optional but recommended. ``` -------------------------------- ### project_get Source: https://docs.rs/ferinth/latest/ferinth/struct.Ferinth.html Retrieves a project by its ID or slug. ```APIDOC ## pub async fn project_get(&self, project_id: &str) -> Result<Project> ### Description Get the project of project_id. The project ID or slug (case-insensitive) can be used. ### Parameters - **project_id** (str) - Required - The ID or slug of the project. ``` -------------------------------- ### List followed projects Source: https://docs.rs/ferinth/latest/src/ferinth/api_calls/user.rs.html Retrieves a list of projects followed by a specific user. ```rust # tokio_test::block_on(async { # let modrinth = ferinth::Ferinth::<ferinth::Authenticated>::new( # env!("CARGO_CRATE_NAME"), # Some(env!("CARGO_PKG_VERSION")), # None, # env!("MODRINTH_TOKEN"), # )?; # let user_id = modrinth.user_get_current().await?.id; let projects = modrinth.user_list_followed_projects(&user_id).await?; # Ok::<_, ferinth::Error>(()) }).unwrap() ``` -------------------------------- ### Get Current User in Rust Source: https://docs.rs/ferinth/latest/src/ferinth/api_calls/user.rs.html Retrieves the user profile associated with the current authorization token. Requires an authenticated Ferinth client instance. ```rust # tokio_test::block_on(async { # let modrinth = ferinth::Ferinth::<ferinth::Authenticated>::new( # env!("CARGO_CRATE_NAME"), # Some(env!("CARGO_PKG_VERSION")), # None, # env!("MODRINTH_TOKEN"), # )?; let current_user = modrinth.user_get_current().await?; // The email should be visible as we are authorised assert!(current_user.email.is_some()); # Ok::<_, ferinth::Error>(()) }).unwrap() ``` -------------------------------- ### team_join Source: https://docs.rs/ferinth/latest/src/ferinth/api_calls/team.rs.html Accepts an invitation to join a team. ```APIDOC ## POST /team/{team_id}/join ### Description Accept an invite to join the team of `team_id`. ### Method POST ### Endpoint /team/{team_id}/join ### Parameters #### Path Parameters - **team_id** (str) - Required - The ID of the team. ``` -------------------------------- ### project_get_dependencies Source: https://docs.rs/ferinth/latest/ferinth/struct.Ferinth.html Retrieves the dependencies for a specific project. ```APIDOC ## pub async fn project_get_dependencies(&self, project_id: &str) -> Result<ProjectDependencies> ### Description Get the dependencies of the project of project_id. ### Parameters - **project_id** (str) - Required - The ID or slug of the project. ``` -------------------------------- ### Format RFC 3339 string with options Source: https://docs.rs/ferinth/latest/ferinth/structures/type.UtcTime.html Demonstrates how to format a DateTime into an RFC 3339 string using specific subsecond precision and timezone formatting options. ```rust let dt = NaiveDate::from_ymd_opt(2018, 1, 26) .unwrap() .and_hms_micro_opt(18, 30, 9, 453_829) .unwrap() .and_utc(); assert_eq!(dt.to_rfc3339_opts(SecondsFormat::Millis, false), "2018-01-26T18:30:09.453+00:00"); assert_eq!(dt.to_rfc3339_opts(SecondsFormat::Millis, true), "2018-01-26T18:30:09.453Z"); assert_eq!(dt.to_rfc3339_opts(SecondsFormat::Secs, true), "2018-01-26T18:30:09Z"); let pst = FixedOffset::east_opt(8 * 60 * 60).unwrap(); let dt = pst .from_local_datetime( &NaiveDate::from_ymd_opt(2018, 1, 26) .unwrap() .and_hms_micro_opt(10, 30, 9, 453_829) .unwrap(), ) .unwrap(); assert_eq!(dt.to_rfc3339_opts(SecondsFormat::Secs, true), "2018-01-26T10:30:09+08:00"); ``` -------------------------------- ### Join a team Source: https://docs.rs/ferinth/latest/src/ferinth/api_calls/team.rs.html Accepts an invitation to join a team. Requires an authenticated client. ```rust # tokio_test::block_on(async { # let modrinth = ferinth::Ferinth::<ferinth::Authenticated>::new( # env!("CARGO_CRATE_NAME"), # Some(env!("CARGO_PKG_VERSION")), # None, # env!("MODRINTH_TOKEN"), # )?; modrinth.team_join("XXXXXXXX").await?; # Ok::<_, ferinth::Error>(()) }).unwrap() ``` -------------------------------- ### User Methods Source: https://docs.rs/ferinth/latest/ferinth/struct.Ferinth.html Methods for retrieving user profiles and their associated projects. ```APIDOC ## user_get ### Description Get the user of `user_id`. ### Signature `pub async fn user_get(&self, user_id: &str) -> Result<User>` ### Parameters - **user_id** (&str) - Required - The user ID. ### Example ```rust let theRookieCoder = modrinth.user_get("7Azq6eD8").await?; ``` ``` ```APIDOC ## user_list_projects ### Description Get the projects of the user of `user_id`. ### Signature `pub async fn user_list_projects(&self, user_id: &str) -> Result<Vec<Project>>` ### Parameters - **user_id** (&str) - Required - The user ID. ### Example ```rust let jellysquid_projects = modrinth.user_list_projects("TEZXhE2U").await?; ``` ``` -------------------------------- ### instance_statistics Source: https://docs.rs/ferinth/latest/src/ferinth/api_calls/misc.rs.html Retrieves various statistics about the Modrinth instance. ```APIDOC ## GET /statistics ### Description Get various statistics about this Modrinth instance. ### Response - **Statistics** - The statistics object containing instance data. ``` -------------------------------- ### project_get_multiple Source: https://docs.rs/ferinth/latest/ferinth/struct.Ferinth.html Retrieves multiple projects by their IDs or slugs. ```APIDOC ## pub async fn project_get_multiple(&self, project_ids: &[&str]) -> Result<Vec<Project>> ### Description Get the projects of project_ids. ### Parameters - **project_ids** (&[&str]) - Required - A slice of project IDs or slugs. ``` -------------------------------- ### List categories Source: https://docs.rs/ferinth/latest/src/ferinth/api_calls/tag.rs.html Retrieves a list of categories, their icons, and applicable project types. ```rust # tokio_test::block_on(async { # let modrinth = ferinth::Ferinth::default(); let categories = modrinth.tag_list_categories().await?; # Ok::<_, ferinth::Error>(()) }).unwrap() ``` -------------------------------- ### version_get Source: https://docs.rs/ferinth/latest/src/ferinth/api_calls/version.rs.html Retrieves details for a specific version by its ID. ```APIDOC ## GET /version/{version_id} ### Description Retrieves the details of a specific version by its ID. ### Method GET ### Endpoint /version/{version_id} ### Parameters #### Path Parameters - **version_id** (str) - Required - The ID of the version. ``` -------------------------------- ### version_get_multiple Source: https://docs.rs/ferinth/latest/src/ferinth/api_calls/version.rs.html Retrieves multiple versions by their IDs. ```APIDOC ## GET /versions ### Description Get the versions of `version_ids`. ### Parameters #### Query Parameters - **ids** (Vec<&str>) - Required - A list of version IDs to retrieve. ``` -------------------------------- ### version_list Source: https://docs.rs/ferinth/latest/src/ferinth/api_calls/version.rs.html Retrieves all versions for a given project ID. ```APIDOC ## GET /project/{project_id}/version ### Description Retrieves a list of all versions associated with the specified project ID. ### Method GET ### Endpoint /project/{project_id}/version ### Parameters #### Path Parameters - **project_id** (str) - Required - The ID of the project. ``` -------------------------------- ### Retrieve a version by hash Source: https://docs.rs/ferinth/latest/ferinth/struct.Ferinth.html Fetches the version associated with a specific SHA1 hash. ```rust // If a mod file has the hash `795d4c12bffdb1b21eed5ff87c07ce5ca3c0dcbf`, we can get the version it belongs to let sodium_version = modrinth.version_get_from_hash("795d4c12bffdb1b21eed5ff87c07ce5ca3c0dcbf").await?; assert_eq!(sodium_version.project_id, "AANobbMI"); ``` -------------------------------- ### Search for projects with pagination Source: https://docs.rs/ferinth/latest/src/ferinth/api_calls/search.rs.html Use search_paged to retrieve a specific number of project results with offset and sorting capabilities. ```rust # use ferinth::structures::search::{Sort, Facet}; # tokio_test::block_on(async { # let modrinth = ferinth::Ferinth::default(); let results = modrinth.search_paged( "sodium", Sort::Relevance, // Limit the number of hits to 12 12, 0, vec![], ).await?; // The amount of hits returned should equal the limit provided assert_eq!(results.hits.len(), 12); # Ok::<_, ferinth::Error>(()) }).unwrap() ``` -------------------------------- ### Search projects with pagination Source: https://docs.rs/ferinth/latest/ferinth/struct.Ferinth.html Performs a paged search for projects with specific sorting and filtering criteria. ```rust let results = modrinth.search_paged( "sodium", Sort::Relevance, // Limit the number of hits to 12 12, 0, vec![], ).await?; // The amount of hits returned should equal the limit provided assert_eq!(results.hits.len(), 12); ```