[][src]Crate serde_url_params

Serde URL Params

This module provides a simple and flexible way for serializing data structures into URL parameters strings.

A data structure can be converted to such string by serde_url_params::to_string function. There is also serde_url_params::to_vec which serializes to a Vec<u8> and serde_url_params::to_writer which serializes to any io::Write such as a File or a TCP stream.

use serde::Serialize;

#[derive(Serialize)]
enum Filter {
    Horror,
    Comedy,
    Thriller,
    Drama,
}

#[derive(Serialize)]
struct Options {
    year: u16,
    actors: Vec<String>,
}

#[derive(Serialize)]
struct SearchRequest {
    film: String,
    per_page: Option<usize>,
    next: Option<usize>,
    filter: Vec<Filter>,
    #[serde(flatten)]
    options: Options,
}

fn main() -> Result<(), serde_url_params::Error> {
    // Some data structure.
    let request = SearchRequest {
        film: String::from("Fight Club"),
        per_page: Some(20),
        next: None,
        filter: vec![Filter::Thriller, Filter::Drama],
        options: Options {
            year: 1999,
            actors: vec!["Edward Norton".into()],
        },
    };

    // Serialize it to a URL parameters string.
    let p = serde_url_params::to_string(&request).unwrap();
    assert_eq!(
        p,
        "film=Fight+Club&per_page=20&filter=Thriller&filter=Drama&year=1999&actors=Edward+Norton"
    );
    Ok(())
}

Almost any type that implements Serde's Serialize trait can be serialized this way. This includes the built-in Rust standard library types Vec<T> as you can see in the above example, as well as structs or enums annotated with #[derive(Serialize)]. However, there are exceptions, for which it is not obvious how to serialize them into flat parameters list:

  • any simple top level value, since it does not have a parameter key, and
  • any nested struct, since it is not obvious how to flatten it,
  • any map, which is not flattened (i.e. annotated with #[serde(flatten)]).

Further, any string is automatically URL encoded (or more precisely, percentage encoded). Elements in Vecs are serialized as repeated key=value pairs, where key is the field holding the vector. Newtype variants and variant structs are flattened by omitting the name of the variant resp. struct.

Modules

error

When serializing to URL parameters fails.

ser

Serialize a Rust data structure into URL parameters string.

Structs

Serializer

A structure for serializing Rust values into URL parameters string.

Enums

Error

Represents all possible errors that can occur when serializing into URL parameters.

Functions

to_string

Serialize the given data structure as a String of URL parameters.

to_vec

Serialize the given data structure as a byte vector containing URL parameters.

to_writer

Serialize the given data structure as URL parameters into the IO stream.

Type Definitions

Result

Alias for Result with error type serde_url_params::Error.