Skip to content

leonholub/rust_rest_example

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

4 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Restful rusty rocket example

Example application to test the use of the rust web framework rocket by building a simple rest API with JWT Auth. Since it bothered me to find so many example applications online with either hard-coded API keys or user databases with plaintext passwords i decided to do a simple one myself to try out a few techniques. Application is by no means complete or secure, this is just some example and notes on several things. Obligatory don't copy-paste this and use it in production or anywhere public.

Feedback is welcome and appreciated.

Features:

  • rocket
  • diesel
  • rust crypto (crates crypt-mac, argon2)
  • Basic REST API (GET, POST)
    • Login Endpoint
    • JWT Authentication
    • example data endpoint

Open TODOs

  • Improve Documentation
  • Clean up code
  • Reorganize dependencies and improve modularity

Database Connection - Diesel

Setup

Spin up your favourite diesel-compatible db engine. I use postgreSQL in this example.

Make sure to have set the database connection in the DATABASE_URL environment variable like this export DATABASE_URL=postgres://<user>:<password>@localhost/<database>

And do the following:

  1. Generate project filesdiesel setup
  2. Generate migration files diesel migration generate <name>
  3. Edit migration files
  4. Apply migration diesel migration run

Optionally run diesel migration redo to test if your down.sql file works, too.

psql -U root webtest

Environment variables

APPLICATION_SECRET - A secret application key used for jwt. Should be random and strong
DATABASE_URL - The url to the postgresql database

Curl commands

Some curl commands to test the API locally

curl --header "Content-Type: application/json" \
  --request POST \
  --data '{"name":"Bike","coolness":100,"wattage":8000,"description":"The coolest thing in the world"}' \
  http://localhost:8000/api/vehicle

curl --header "Content-Type: application/json" \
  --request PUT \
  --data '{"id":2, "name":"Roadbike","coolness":101,"wattage":8000,"description":"The coolest thing in the world"}' \
  http://localhost:8000/api/vehicle/2

curl --header "Authentication: XYZ-token" --request GET -I http://localhost:8000/

curl --header "Content-Type: application/json" \
  --request POST \
  --data '{"username":"leon", "password": "xyz"}' \
  http://localhost:8000/login

Reading List

About

Example application building a REST API in rust using rocket, diesel and jwt.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published