Lecture: Building a Backend Using Rust, Actix-Web, and SurrealDB
Introduction
- Objective: Learn how to build a backend using Rust, Actix-Web framework, and SurrealDB as the data layer.
Demo and Project Setup
- Tools: Postman for API demonstration
- Endpoints:
- GET
/pizzas
: Get a list of pizzas
- POST
/buy_pizza
: Buy a pizza
- PATCH
/update_pizza
: Update a pizza
- Initial Rust Project Creation:
- Create Rust project using
cargo new r_backend
- Navigate to project:
cd r_backend
- Default structure has
Cargo.toml
and src
folder
Adding Dependencies
- Required Crates:
actix-web
: Web framework
serde-json
: JSON format handling
serde
: Serialization/Deserialization
surrealdb
: Database handling
uuid
: Unique ID generation
validator
: Data validation
async-std
: Async functions
derive_more
: Additional derive features
- Installation: Add these dependencies in
Cargo.toml
and build: cargo build
Writing Initial Code
- Endpoint handlers:
- Define endpoint routes using Actix-Web macros
- Implement basic GET, POST, PATCH handlers
- Set up the main function with Actix-Web server
- Use async functions for web handling
- Building and Running: Run using
cargo run
or cargo watch
Creating Models
- Define
buy_pizza_request
struct in models/pizza.rs
- Use
serde
for serialization
- Use
validator
for validation
- Configure
models/mod.rs
and main.rs
to include new models
Handling Database (SurrealDB)
- Initialization: Set up and initialize SurrealDB
- Install SurrealDB and check connection with Postman
- Create
db/database.rs
for database interaction
- Database Struct: Define
Database
struct and implement init
function for connection
Implementing CRUD Operations
- GET pizzas: Fetch data from SurrealDB
- Implement
get_all_pizzas
function in database.rs
- POST buy_pizza: Add pizza data to SurrealDB
- Implement data validation and pizza creation
- PATCH update_pizza: Update pizza data in SurrealDB
- Fetch pizza by UUID and update it
Error Handling
- Custom Errors: Create
pizza_error
in errors.rs
- Define error cases:
NoPizzasFound
, PizzaCreationFailure
, NoSuchPizzaFound
- Implement error responses using Actix-Web
Refactoring with Traits
- Creating Traits: Define
pizza_data_trait.rs
for pizza operations
- Implement
PizzaDataTrait
for database interactions
- Code Refactoring: Move functions to trait implementation
- Update endpoint handlers to use new trait functions
Conclusion
- Summary: Demonstrated how to build and update APIs in Rust using Actix-Web and SurrealDB
- Maintenance: Discussed the organization of code using traits for long-term maintainability
- Next Steps: Encourage adding more endpoints and exploring additional features
Final Thoughts
- Improvements: Emphasized code maintainability using traits
- Engagement: Suggested subscribing, liking, and sharing for more content
Stay Awesome and Stay Safe ❤