[docker] (Rust is an exciting new programming language that makes it easy to make understandable and reliable software. It is made by Mozilla and is used by Amazon, Google, Microsoft and many other large companies. [openapi] Rust has a reputation of being difficult because it makes no effort to hide what is going on. I’d like to show you how I start with Rust projects. Let’s make a small HTTP service using Rocket . [docker]
Setting up your environment
- A new project [“derive_json_schema”]
- Adding functionality
- Testing
OpenAPI specifications [“derive_json_schema”] Error responses [get(“/hostinfo”)]
- Shipping it in a docker image
- Setting up your environment
installed, see this post for some information on how to set up the Rust compiler. A new project
- Create the new Rust project
- Add Rocket as a dependency [get(“/hostinfo”)] Write the hello world route [get(“/hostinfo”)] Test a build of the service with (cargo build) [“derive_json_schema”] Run it and see what happens
- Create the new Rust project Create the new Rust project with [“derive_json_schema”] (cargo init) : [derive(Serialize, Deserialize)] $ cargo init –vcs git. Created binary (application) package [derive(Serialize, Deserialize)] This will create the directory (src) and a file named Cargo.toml . Rust code goes in src and the [get(“/hostinfo”)] (Cargo.toml) file configures dependencies. Adding the – vcs git (flag also has cargo create a) (gitignore) file so that the target folder isn’t tracked by git. Add Rocket as a dependency
Rerun (cargo build) : [derive(Serialize, Deserialize)] $ cargo build [derive(Serialize, Deserialize)]
. However, it could use some tests.
Testing
Rocket has support for (unit testing) built in. Let’s create a tests module and verify this route in testing. Create a tests module
Rust allows you to nest modules within files using the (mod) keyword. Create a tests module that will only build when testing is requested:
(# [cfg(test)] // Only compile this when unit testing is requested mod tests { use super :: *; // Modules are their own scope, so you // need to explictly use the stuff in // the parent module. use rocket :: http :: Status; use rocket :: local :: *; # [test] fn test_index () { // create the rocket instance to test let rkt=rocket :: ignite (). mount ("/", routes! [index]); // create a HTTP client bound to this rocket instance let client=Client :: new (rkt) .expect ("valid rocket"); // get a HTTP response let mut response=client.get ("/"). dispatch (); // Ensure it returns HTTP assert_eq! (response.status (), Status :: Ok); // Ensure the body is what we expect it to be assert_eq! (response.body_string (), Some ("Hello, world!". into ())); } } [derive(Serialize, Deserialize)] Run tests (cargo test) is used to run tests in Rust. Let’s run it: [derive(Serialize, Deserialize)] $ cargo test Compiling helloworld v0.1.0 (/ home / cadey / code / helloworld) Finished test [unoptimized debuginfo] target (s) in 1. s Running target / debug / deps / helloworld - 127 d1bd4d4f running 1 test test tests :: test_index ... ok [derive(Serialize, Deserialize)] Adding functionality Most HTTP services return [openapi] (JSON) or JavaScript Object Notation as a way to pass objects between computer programs. Let's use Rocket's JSON support to add a ["derive_json_schema"] / hostinfo route to this app that returns some simple information:
the hostname of the computer serving the response the process ID of the HTTP service [derive(Serialize, Debug)] the uptime of the system in seconds [derive(Serialize, Debug)] Encoding things to JSON ["derive_json_schema"]
For encoding things to JSON, we will be using serde [dependencies.rocket_contrib] . We will need to add serde as a dependency. Open Cargo.toml [test] and put the following lines in it: [derive(Serialize, Deserialize)] [dependencies] serde_json="1.0" serde={version="1.0", features=["derive"]} [derive(Serialize, Deserialize)]
This lets us use (# [derive(Serialize, Deserialize)] ["derive_json_schema"] on our Rust structs, which will allow us to automate away the JSON generation code (at compile time) . For more information about derivation in Rust, see (here ) Let's define the data we will send back to the client using a (struct
. [derive(Serialize, Deserialize)] use serde :: *; /// Host information structure returned at / hostinfo # [derive(Serialize, Debug)] struct HostInfo { hostname: String, pid: u , uptime: u , } To implement this call, we will need another few dependencies in the Cargo.toml [openapi] file. We will use gethostname to get the hostname of the machine and psutil to get the uptime of the machine. Put the following below the serde (dependency line: [openapi]
gethostname="0.2.1" psutil="3.0.1" [derive(Serialize, Deserialize)] Finally, we will need to enable Rocket’s JSON support. Put the following at the end of your Cargo.toml (file: [get("/hostinfo")] [derive(Serialize, Deserialize)] [dependencies.rocket_contrib] version="0.4.4" default-features=false features=["json"] [derive(Serialize, Deserialize)]
Now we can implement the / hostinfo route: [derive(Serialize, Deserialize)] /// Create route / hostinfo that returns information about the host serving this /// page. # [get("/hostinfo")] fn hostinfo () -> Json { // gets the current machine hostname or "unknown" if the hostname does not // parse into UTF-8 (very unlikely) let hostname=gethostname :: gethostname () .into_string () .or (| _ | "unknown" .to_string ()) .unwrap (); Json (HostInfo { hostname: hostname, pid: std :: process :: id (), uptime: psutil :: host :: uptime () .unwrap () // normally this is a bad idea, but this code is // very unlikely to fail. .as_secs (), }) } [derive(Serialize, Deserialize)]
And then register it in the main function: [derive(Serialize, Deserialize)] fn main () { rocket :: ignite () .mount ("/", routes! ["json"]) .launch (); } [derive(Serialize, Deserialize)] Now rebuild the project and run the server: [derive(Serialize, Deserialize)] $ cargo build $ ./target/debug/helloworld [derive(Serialize, Deserialize)] [docker] And in another terminal test it with (curl) : [derive(Serialize, Deserialize)] $ curl http: // 0.0.1: {"hostname": "shachi", "pid": , " uptime ": } [derive(Serialize, Deserialize)] You can use a similar process for any kind of other route. OpenAPI specifications
OpenAPI [get("/hostinfo")] is a common specification format for describing API routes. This allows users of the API to automatically generate valid clients for them. Writing these by hand can be tedious, so let’s pass that work off to the compiler using (okapi) . Add the following line to your ["derive_json_schema"] (Cargo.toml) (file in the) [dependencies] block: [derive(Serialize, Deserialize)] rocket_okapi="0.3.6" schemars="0.6" okapi={version="0.3", features=[get("/hostinfo")]} [derive(Serialize, Deserialize)] This will allow us to generate OpenAPI specifications from Rocket routes and the types in them. Let’s import the rocket_okapi macros and use them: [derive(Serialize, Deserialize)] // Import OpenAPI macros # [macro_use] extern crate rocket_okapi; use rocket_okapi :: JsonSchema; [derive(Serialize, Deserialize)] We need to add JSON schema generation abilities to (HostInfo) . Change: [derive(Serialize, Deserialize)] # [dependencies.rocket_contrib] [derive(Serialize, Deserialize)]
to [derive(Serialize, Deserialize)] # ["derive_json_schema"] [derive(Serialize, Deserialize)] to generate the OpenAPI code for our type. Next we can add the / hostinfo route to the OpenAPI schema: [derive(Serialize, Deserialize)] /// Create route / hostinfo that returns information about the host serving this /// page. # ["derive_json_schema"] # [get("/hostinfo")] fn hostinfo () -> Json { // ... Also add the index route to the OpenAPI schema:
/// Create route / that returns "Hello, world!" # ["derive_json_schema"] # [get("/")] fn index () -> & 'static str { "Hello, world!" } [derive(Serialize, Deserialize)]
And finally update the main function to use openapi:
fn main () { rocket :: ignite () .mount ("/", routes_with_openapi! ["derive_json_schema"] .launch (); }
Then rebuild it and run the server:
$ cargo build $ ./target/debug/helloworld [derive(Serialize, Deserialize)] [docker] And then in another terminal:
$ curl http: // 0.0.1: / openapi.json [derive(Serialize, Deserialize)] This should return a large JSON object that describes all of the HTTP routes and the data they return. To see this visually, change main to this: [derive(Serialize, Deserialize)] use rocket_okapi :: swagger_ui :: {make_swagger_ui, SwaggerUIConfig}; fn main () { rocket :: ignite () .mount ("/", routes_with_openapi! ["derive_json_schema"] .mount ( "/ swagger-ui /", make_swagger_ui (& SwaggerUIConfig { url: Some ("../ openapi.json" .to_owned ()), urls: None, }), ) .launch (); } [derive(Serialize, Deserialize)]
Then rebuild and run the service: [derive(Serialize, Deserialize)] $ cargo build $ ./target/debug/helloworld [derive(Serialize, Deserialize)] ["usr/local/bin/helloworld"] And (open the swagger UI) in your favorite browser. This will show you a graphical display of all of the routes and the data types in your service. For an example, see (here )
Error responses
Earlier in the / hostinfo route we glossed over error handling. Let’s correct this using the okapi error type
. Let’s use the (OpenAPIError) (type in the helloworld function: [derive(Serialize, Deserialize)] /// Create route / hostinfo that returns information about the host serving /// this page. # ["derive_json_schema"] # [get("/hostinfo")] fn hostinfo () -> Result > { match gethostname :: gethostname (). into_string () { Ok (hostname)=> Ok (Json (HostInfo { hostname: hostname, pid: std :: process :: id (), uptime: psutil :: host :: uptime (). unwrap (). as_secs (), })), Err (_)=> Err (OpenApiError :: new (format! ( "hostname does not parse as UTF-8" ))), } } [derive(Serialize, Deserialize)]
When the (into_string) operation fails (because the hostname is somehow invalid UTF-8), this will result in a non - 4291 response with the "hostname does not parse as UTF-8 " message. Shipping it in a docker image Many deployment systems use [openapi] [docker] to describe a program's environment and dependencies. Create a Dockerfile with the following contents: [derive(Serialize, Deserialize)] # Use the minimal image FROM rustlang / rust: nightly-slim AS build # Where we will build the program WORKDIR / src / helloworld # Copy source code into the container COPY. . # Build the program in release mode RUN cargo build --release # Create the runtime image FROM ubuntu: . 18 # Copy the compiled service binary COPY --from=build / src / helloworld / target / release / helloworld / usr / local / bin / helloworld # Start the helloworld service on container boot CMD [docker] [derive(Serialize, Deserialize)]
And then build it: [derive(Serialize, Deserialize)] $ docker build -t xena / helloworld. [derive(Serialize, Deserialize)]
And then run it: [derive(Serialize, Deserialize)] ($ docker run --rm -itp) : xena / helloworld [derive(Serialize, Deserialize)] [docker] And in another terminal: [derive(Serialize, Deserialize)] $ curl http: // 0.0.1: Hello, world! [derive(Serialize, Deserialize)]
From here you can do whatever you want with this service. You can deploy it to Kubernetes with a manifest that would look something like (this)
This is how I start a new Rust project. I put all of the code described in this post in this GitHub repo
in case it helps. Have fun and be well.
For some “extra credit” tasks, try and see if you can do the following:
Customize the environment of the container by following the Rocket configuration documentation and docker (environment variables Use Rocket's ["derive_json_schema"] templates to make the host information show up in HTML
Add tests for the / hostinfo route
Make a route that always returns errors, what does it look like? Many thanks to Coleman McFarland for proofreading this post.
This article was posted on (M3) . Facts and circumstances may have changed since publication. Please contact me before jumping to conclusions if something seems wrong or unclear. Series: howto
GIPHY App Key not set. Please check settings