All Projects → spietika → Restson Rust

spietika / Restson Rust

Licence: mit
Easy-to-use REST client for Rust programming language

Programming Languages

rust
11053 projects

Labels

Projects that are alternatives of or similar to Restson Rust

Behat Api Extension
API extension for Behat, used to ease testing of JSON-based APIs
Stars: ✭ 92 (-1.08%)
Mutual labels:  rest, json
Apicache
Simple API-caching middleware for Express/Node.
Stars: ✭ 957 (+929.03%)
Mutual labels:  rest, json
Ps Webapi
(Migrated from CodePlex) Let PowerShell Script serve or command-line process as WebAPI. PSWebApi is a simple library for building ASP.NET Web APIs (RESTful Services) by PowerShell Scripts or batch/executable files out of the box.
Stars: ✭ 24 (-74.19%)
Mutual labels:  rest, json
Restclient
🦄 Simple HTTP and REST client for Unity based on Promises, also supports Callbacks! 🎮
Stars: ✭ 675 (+625.81%)
Mutual labels:  rest, json
Generator Http Fake Backend
Yeoman generator for building a fake backend by providing the content of JSON files or JavaScript objects through configurable routes.
Stars: ✭ 49 (-47.31%)
Mutual labels:  rest, json
Ky
🌳 Tiny & elegant JavaScript HTTP client based on the browser Fetch API
Stars: ✭ 7,047 (+7477.42%)
Mutual labels:  rest, json
Fastapi
FastAPI framework, high performance, easy to learn, fast to code, ready for production
Stars: ✭ 39,588 (+42467.74%)
Mutual labels:  rest, json
Jikan
Unofficial MyAnimeList PHP+REST API which provides functions other than the official API
Stars: ✭ 531 (+470.97%)
Mutual labels:  rest, json
Api Client Generator
Angular REST API client generator from Swagger YAML or JSON file with camel case settigs
Stars: ✭ 92 (-1.08%)
Mutual labels:  rest, json
Dito
Dito.js is a declarative and modern web framework with a focus on API driven development, based on Objection.js, Koa.js and Vue.js – Released in 2018 under the MIT license, with support by Lineto.com
Stars: ✭ 44 (-52.69%)
Mutual labels:  rest, json
Kafka Pixy
gRPC/REST proxy for Kafka
Stars: ✭ 613 (+559.14%)
Mutual labels:  rest, json
Json Api Dart
JSON:API client for Dart/Flutter
Stars: ✭ 53 (-43.01%)
Mutual labels:  rest, json
Rest Assured
Java DSL for easy testing of REST services
Stars: ✭ 5,646 (+5970.97%)
Mutual labels:  rest, json
Droidparts
Stars: ✭ 785 (+744.09%)
Mutual labels:  rest, json
Spyke
Interact with REST services in an ActiveRecord-like manner
Stars: ✭ 591 (+535.48%)
Mutual labels:  rest, json
Rest Api Examples
Test and Prototype with Fake Online REST/OAuth 2 APIs Examples
Stars: ✭ 13 (-86.02%)
Mutual labels:  rest, json
Networking
⚡️ Elegantly connect to a REST JSON Api. URLSession + Combine + Decodable + Generics = <3
Stars: ✭ 499 (+436.56%)
Mutual labels:  rest, json
Pmhttp
Swift/Obj-C HTTP framework with a focus on REST and JSON
Stars: ✭ 509 (+447.31%)
Mutual labels:  rest, json
Hyperpotamus
🥋 YAML/JSON automation scripting 🤺
Stars: ✭ 38 (-59.14%)
Mutual labels:  rest, json
Flask Restx
Fork of Flask-RESTPlus: Fully featured framework for fast, easy and documented API development with Flask
Stars: ✭ 1,050 (+1029.03%)
Mutual labels:  rest, json

crates.io License: MIT Docs: latest

Restson Rust

Easy-to-use REST client for Rust programming language that provides automatic serialization and deserialization from Rust structs. The library is implemented using Hyper and Serde JSON.

Getting started

Add the following lines to your project Cargo.toml file:

[dependencies]
restson = "^0.7"
serde = "^1.0"
serde_derive = "^1.0"

This adds dependencies for the Restson library and also for Serde which is needed to derive Serialize and Deserialize for user defined data structures.

Data structures

Next, the data structures for the REST interface should be defined. The struct fields need to match with the API JSON fields. The whole JSON does not need to be defined, the struct can also contain a subset of the fields. Structs that are used with GET should derive Deserialize and structs that are used with POST should derive Serialize.

Example JSON (subset of http://httpbin.org/anything response):

{
  "method": "GET", 
  "origin": "1.2.3.4", 
  "url": "https://httpbin.org/anything"
}

Corresponding Rust struct:

#[macro_use]
extern crate serde_derive;

#[derive(Serialize,Deserialize)]
struct HttpBinAnything {
    method: String,
    url: String,
}

These definitions allow to automatically serialize/deserialize the data structures to/from JSON when requests are processed. For more complex scenarios, see the Serde examples.

Rest paths

In Restson library the API resource paths are associated with types. That is, the URL is constructed automatically and not given as parameter to requests. This allows to easily parametrize the paths without manual URL processing and reduces URL literals in the code.

Each type that is used with get/post needs to implement RestPath trait. The trait can be implemented multiple times with different generic parameters for the same type as shown below. The get_path can also return error to indicate that the parameters were not valid. This error is propagated directly to the client caller.

// plain API call without parameters
impl RestPath<()> for HttpBinAnything {
    fn get_path(_: ()) -> Result<String,Error> { Ok(String::from("anything")) }
}

// API call with one u32 parameter (e.g. "http://httpbin.org/anything/1234")
impl RestPath<u32> for HttpBinAnything {
    fn get_path(param: u32) -> Result<String,Error> { Ok(format!("anything/{}", param)) }
}

Requests

To run requests the client instance needs to be created first. The base URL of the resource is given as parameter:

let mut client = RestClient::new("http://httpbin.org").unwrap();

This creates a client instance with default configuration. To configure the client, it is created with a Builder

let mut client = RestClient::builder().dns_workers(1)
        .build("http://httpbin.org").unwrap();

GET

The following snippet shows an example GET request:

// Gets https://httpbin.org/anything/1234 and deserializes the JSON to data variable
let data: HttpBinAnything = client.get(1234).unwrap();

The get and post functions call the get_path function automatically from RestPath based on the parameter type to construct the URL. If the compiler is able to infer the parameter and return value types from the context (as shown above), they do not need to be annotated. The call above is equivalent with:

let data = client.get::<u32, HttpBinAnything>(1234).unwrap();

Restson also provides get_with function which is similar to the basic get but it also accepts additional query parameters that are added to the request URL.

// Gets http://httpbin.org/anything/1234?a=2&b=abcd
let query = vec![("a","2"), ("b","abcd")];
let data: HttpBinAnything = client.get_with(1234, &query).unwrap();

Both GET interfaces return Result<T, Error> where T is the target type in which the returned JSON is deserialized to.

POST

The following snippets show an example POST request:

#[derive(Serialize)]
struct HttpBinPost {
    data: String,
}

impl RestPath<()> for HttpBinPost {
    fn get_path(_: ()) -> Result<String,Error> { Ok(String::from("post")) }
}
let data = HttpBinPost { data: String::from("test data")};
// Posts data to http://httpbin.org/post
client.post((), &data).unwrap();

In addition to the basic post interface, it is also possible to provide query parameters with post_with function. Also, post_capture and post_capture_with interfaces allow to capture and deserialize the message body returned by the server in the POST request.

PUT

HTTP PUT requests are also supported and the interface is similar to POST interface: put, put_with, put_capture and put_capture_with functions are available.

PATCH

HTTP PATCH requests are also supported and the interface is similar to POST and PUT interface: patch and patch_with functions are available.

DELETE

Restson supports HTTP DELETE requests to API paths. Normally DELETE request is sent to API URL without message body. However, if message body or query parameters are needed, delete_with can be used. Moreover, the response status code from server is checked, but the response body is not captured.

Similarly with other requests, the path is obtained from RestPath trait.

struct HttpBinDelete {
}

impl RestPath<()> for HttpBinDelete {
    fn get_path(_: ()) -> Result<String,Error> { Ok(String::from("delete")) }
}

The delete function does not return any data (only possible error) so the type needs to be annotated.

// DELETE request to http://httpbin.org/delete
let mut client = RestClient::new("http://httpbin.org").unwrap();
client.delete::<(), HttpBinDelete>(()).unwrap();

JSON with array root element

In all of the examples above the JSON structure consists of key-value pairs that can be represented with Rust structs. However, it is also possible that valid JSON has array root element without a key. For example, the following is valid JSON.

["a","b","c"]

It is possible to work with APIs returning arrays in Restson. However instead of a struct, the user type needs to be a container. Vec<String> in this case. The type also needs to implement the RestPath trait as explained before, and easiest way to do so is to wrap the container in a struct.

#[derive(Serialize,Deserialize,Debug,Clone)]
struct Products ( pub Vec<Product> );

#[derive(Serialize,Deserialize,Debug,Clone)]
pub struct Product {
    pub name: String,
    //...
}

impl RestPath<()> for Products {
    fn get_path(_: ()) -> Result<String,Error> { Ok(String::from("/api/objects/products"))}
}

pub fn products(&self) -> Vec<Product> {
    let mut client = RestClient::new("http://localhost:8080").unwrap();
    client.get::<_, Products>(()).unwrap().0
}

Relative paths

It is possible to use relative paths in the base URL to avoid having to return version or other prefix from the get_path() implementation. For instance, endpoint http://localhost:8080/api/v1/ep could be handled by setting http://localhost:8080/api/v1/ as base URL and returning ep from the get_path(). Note: the trailing slash in the base URL is significant! Without it, the last element is replaced instead of appended when the elements are joined (see here for more information).

Body wash

For some APIs it is necessary to remove magic values or otherwise clean/process the returned response before it is deserialized. It is possible to provide a custom processing function with set_body_wash_fn() which is called with the raw returned body before passing it to the deserialization step.

Logging

The library uses the log crate to provide debug and trace logs. These logs allow to easily see both outgoing requests as well as incoming responses from the server. See the log crate documentation for details.

Examples

For more examples see tests directory.

License

The library is released under the MIT license. See LICENSE for details.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].