Rust Rocket Sample

screenshot of Rust Rocket Sample

Rust Rocket Sample

Fully working CRUD REST API example using Rust and Rocket.rs

Overview

rust-rocket-sample is a fully working CRUD REST API example built using Rust and the Rocket framework. It demonstrates various features such as connecting to MongoDB, handling errors, implementing CORS, and generating API documentation using okapi. It also provides test codes to verify the functionality of the API endpoints.

Features

  • MongoDB Connection: Establishes a connection to MongoDB using a custom fairing in Rocket.
  • Custom Error Handling: Implements error handling using Rocket Responder and okapi OpenApiGenerator.
  • CORS and Counter Fairing: Demonstrates the usage of fairings by implementing CORS and Counter fairings.
  • Customer Model: Includes an example model called "Customer" to showcase how Rust structs interact with MongoDB.
  • Request Guard: Implements a request guard using ApiKey to secure the REST API endpoints.
  • CRUD Endpoints: Provides simple CRUD endpoints using the Customer model.
  • Open API Documentation: Implements Open API documentation using okapi to automatically generate API documentation.
  • Testing: Provides test codes to validate the functionality of the API endpoints.

Installation

To run the rust-rocket-sample project, follow these steps:

  1. Create a .env file and add the following environment variables:

    • MONGO_URI: MongoDB connection URI.
    • MONGO_DB_NAME: Name of the MongoDB database.
    • API_KEY: API key for securing the REST API endpoints.
  2. Build and run the project in debug mode:

    cargo run
    
  3. Build and run the project in release mode:

    cargo build --release
    cargo run --release
    
  4. To run the unit tests, use the following command:

    cargo test
    

Summary

rust-rocket-sample is a comprehensive example of building a CRUD REST API using Rust and the Rocket framework. It covers various features including MongoDB integration, error handling, fairings, request guards, and API documentation generation. The provided test codes ensure the functionality of the API endpoints.