Crates.io | jplaceholder |
lib.rs | jplaceholder |
version | 1.5.1 |
source | src |
created_at | 2018-08-26 02:04:21.89002 |
updated_at | 2018-08-28 02:59:10.190252 |
description | A Rust library for the JSON Placeholder API |
homepage | https://github.com/WebD-EG/Jplaceholder-Rust |
repository | https://github.com/WebD-EG/Jplaceholder-Rust |
max_upload_size | |
id | 81453 |
size | 15,436 |
A Rust library for the JSON Placeholder API Documentation: https://docs.rs/jplaceholder/1.0.1/jplaceholder/
extern crate jplaceholder;
use jplaceholder::Model;
use jplaceholder::Post;
match Post::find(2) {
Some(post) => println!("Title of the article {}: {}", post.id, post.title),
None => println!("Article not found!")
}
To install the library, you just have to put it into your Cargo.toml file:
jplaceholder = "1.0.1"
Then, require the library into your main file.
extern crate jplaceholder;
The model trait provides usefull methods to interact with the resources.
Finds a resource by its ID
Example:
use jplaceholder::Model;
use jplaceholder::Post;
match Post::find(2) {
Some(post) => println!("Title of the article {}: {}", post.id, post.title),
None => println!("Article not found!")
}
Gets all of the resources
Example:
use jplaceholder::Model;
use jplaceholder::Post;
let posts: Vec<Post> = Post::all();
for post in posts {
println!("The title of the post {} is: {}", post.id, post.title)
}
Creates a new resource
Example:
use jplaceholder::Model;
use jplaceholder::Post;
let post = Post{id: 5, title: String::from("Hey"), body: String::from("hehe"), user_id: 5};
Post::create(post);
Relationships let you interact between models. Let's say that I get the first user like this:
use jplaceholder::Model;
use jplaceholder::User;
use jplaceholder::Post;
let user = match User::find(1) {
Some(u) => u,
None => panic!("user not found")
};
Now, if I want to get all of the articles posted by this user:
// .......
let posts: Vec<Post> = user.posts().expect("This user has posted no article");
println!("{} posted {} articles", user.name, posts.len());
And conversely, if I want to get the user that posted an article:
use jplaceholder::Model;
use jplaceholder::Post;
if let Some(post) = Post::find(1) {
match post.user() {
Some(user) => println!("{} has posted this article", user.name),
None => println!("Author not found")
}
}