Crud Api
This crate provides a framework to generate an executable to manipulate your HTTP API from CLI.
The apps using this lib can replace your curl queries when you need to access to your favorite API.
Features
API:
- data are encoded in JSON. It don't support XML, grpc, ...
- output can be formated on json, yaml, toml, csv or tsv
- output stream on stdout or in a file
Tutorial
Let's create an CLI for jsonplaceholder API.
For the impatients, the whole code of this example can be found in examples/jsonplaceholder_api.rs
First add these dependencies to Cargo.toml:
[]
= "0.4"
= "0.5"
= "4.3"
= { = "0.1", ="../crud/crud-api", =false, =["toml","json","yaml"]}
= { = "0.1", ="../crud/crud-auth"}
= { = "0.1", ="../crud/crud-auth-bearer"}
= { = "0.14", = ["client","http1"] }
= "0.5"
= { = "5.9", = ["fancy"] }
= { = "1", = ["full"] }
= { = "1.0", = ["derive"] }
# To force static openssl
= { = "0.10", = ["vendored"] }
Now, create a minimal runner stucture and a main function.
ApiRun on JSONPlaceHolder derives all the CLI.
use ApiRun;
use CrudAuth;
use Auth;
use ;
;
async
[crud_api_endpoint::ApiRun] accepts some parameters. They are documented in crud_api_endoint crate.
Let's customize our CLI with a base_url for our API, a name used in the documentation and the settings. qualifier and organisation is used to compute the settings location and env_prefix is the prefix of the environment variables
;
Before creating the first endpoint we need to describe its output structure.
use ;
Now, we can declare the endpoint. The minimal parameters are:
route, the target api route.cli_route, the route transcipted as cli arguments. Each slash separate a subcommand. The other parameters can found in [crud_api_endpoint::Api] and [crud_api_endpoint::Enpoint] structs documentation.
use Api;
We can create more complex enpoint. Let's create an edit route.
- The
routeparameter takes a post'sidargument. This argument should be present in thecli_route. - the HTTP method is set with the
methodparameter. - Some help can be provided via the parameters
cli_helpandcli_long_help. - the payload is described by the struct declared with the
payload_struct. The query parameter can be add with thequery_structparameter.
In this step, the payload structure is PostCreate (the same structure is used for both creation and update). PostCreate derives ApiInput. All PostCreate fields parameters are describe in the [crud_api_endpoint::ApiInputConfig] structs.
use ;
Output Customization
Tables
Results arrays are formatted using the crate crud-tidy-viewer.
The available table column options are:
table_skip: don't display this field in the table.table_format: format this field in table.- date formatter:
date(format = "%Y-%m-%d %H:%M:%S")
- date formatter:
Pretty Structures
The crate crud-pretty-struct can format a single (json) struct.