1
0
Fork
You've already forked canapi
0
Define your API once, use it on server and client. DEPRECATED, look at the hsr crate for a replacement.
  • Rust 100%
Find a file
Baptiste Gelez 3a5899f28e
Merge pull request #3 from Plume-org/derive-trait
Derive Debug and Clone for Error
2018年12月25日 09:40:34 +01:00
src Derive Debug and Clone for Error 2018年12月24日 20:14:33 +01:00
.gitignore Initial commit 2018年09月15日 18:11:39 +01:00
Cargo.toml Version bump: 0.2.0 2018年10月07日 14:49:15 +01:00
README.md Initial commit 2018年09月15日 18:11:39 +01:00

Canapi

Common Canapi traits.

Canapi is a collection of Rust crate to make it possible to share a REST API definition between clients and servers. You define your endpoints (Endpoint trait), bind them to your databse (Provider trait), and you can re-use these endpoints in your client (Fetch trait).

This requires three separate crates: one for your API defintion, one for your server, and one for the client.

Example

my-api, where you define the API.

usecanapi::Endpoint;#[derive(Default, Serialize, Deserialize)]struct UserEndpoint{id: Option<i32>,name: Option<String>,bio: Option<String>,}implEndpointforPostEndpoint{type Id=i32;fn endpoint()-> &'static str {"/api/v1/users"}}

my-server, to bind endpoints to database (and expose them to the rest of the world)

usecanapi::Provider;usediesel::*;// Example with Diesel
usemy_api::UserEndpoint;/// Define the User model...
implProvider<PgConnection>forUser{type Data=UserEndpoint;fn get(conn: &PgConnection,id: i32)-> Option<Post>{posts::table.filter(posts::id.eq(id)).limit(1).get_result::<Post>(conn).ok()}}// Use rocket, actix-web, iron, gotham or whatever you want to expose your endpoints...

my-client, to use your API (here with a potential WASM Fetch impl)

usecanapi_wasm::WasmFetch;useplume_api;#[derive(Default)]pubstruct Api{users: UserEndpoint}fn fetch_first_post(){letapi=Api::default();letpost=api.users.get::<WasmFetch>(1);assert_eq(post.id,Some(1));}fn find_hello(){letapi=Api::default();letpost=api.users.find::<WasmFetch>(PostEndpoint{name: Some(String::new("Jane")),..PostEndpoint::default()});assert_eq!(post.title,Some(String::new("Jane")));}