Building RESTful API server in Rust with nickel-postgres

Following on from my first Rust program, I have created my first Rust library, nickel-postgres.

nickel-postgres on Github

You can use it in your projects by adding this to Cargo.toml:

[dependencies.nickel_postgres]

git = "https://github.com/bguiz/nickel-postgres.git"
rev = "feature/init"

Here is a sample webserver that demonstrates how to create a RESTful API using Nickel.rs and nickel-postgres, and includes a demo front end to test it out.

Here is how - First off, import the crate and middlware class:

extern crate nickel_postgres;
use nickel_postgres::PostgresMiddleware;

Next, add instantiate PostgresMiddleware, and add it to your instance of Nickel:

let mut server = Nickel::new();
let postgres_middleware: PostgresMiddleware = PostgresMiddleware::new(
    "postgres://postgres:postgres@localhost", postgres::NoSsl, 5);
server.utilize(postgres_middleware);

Finally, within each HTTP request handler functions, obtain a database connection:

fn a_handler_function(req: &Request, response: &mut Respose) {
    let db_conn = req.map.find::<PooledPostgresConnection>().unwrap();
    // use db_conn
}

That is all, enjoy!

Many thanks to Christoph Burgdorf, creator of Nickel.rs, and Steve Fackler, author of rust-postgres, for giving me a number of pointers to get things going.

Are we web yet? … one step closer!

Copyright © 2008-present Brendan Graetz