Skip to main content

Writing your first Graphul API

Installing Rust​

If you don’t have Rust yet, we recommend you use rustup to manage your Rust installation. The official rust guide has a wonderful section on getting started.

Graphul currently has a minimum supported Rust version 1.60. Running rustup update will ensure you have the latest and greatest Rust version available. As such, this guide assumes you are running Rust 1.60 or later.

Hello World!​

Let's write our first Graphul application! Start by creating a new binary-based Cargo project and changing into the new directory:

cargo new hello-world
cd hello-world

Add Graphul as a dependency​

Add graphul as a dependency of your project by adding the following to your Cargo.toml file.

Besides we choose Tokio as asynchronous Rust runtime for this example but you can use whatever you like.

So your Cargo.toml should have something like this.

[dependencies]
graphul = "0.5.6"
tokio = { version = "1.26.0", features = ["full"] }
tip

In the new versions of Rust you can run a command like this:

cargo add graphul tokio --features tokio/full
For Graphul devs:

Development versions must be git dependencies.

To depend on a development version of Graphul, you'll need to point Cargo.toml to a Graphul git repository.

[dependencies]
graphul = { git = "https://github.com/graphul-rs/graphul" }

Editing main.rs​

Copy and paste these few lines of code into the file main.rs, we are going to explain:

src/main.rs
use graphul::{http::Methods, Graphul};

#[tokio::main]
async fn main() {
let mut app = Graphul::new();

app.get("/", || async { "Hello, World πŸ‘‹!" });

app.run("127.0.0.1:8000").await;
}

In line 3 we found a macro!

#[tokio::main]

In short #[tokio::main] initialize an async runtime.

This macro is from the library Tokio. We recommend reading this article about the macro for more information.

In line 5 we instance Graphul and save it in the variable app.

    let mut app = Graphul::new();

Then in line 7, we access a method of the variable app (The instance of Graphul). It is the method get.

Graphul provides a method for every HTTP request method.

In this function/method of the variable, we need to pass two parameters

    app.get("/", || async { "Hello, World πŸ‘‹!" });

The first is the access route and the second, is an executable function for when a request is going to be received.

In this case, we are using a closure of Rust that return "Hello, World πŸ‘‹!"

Finally, into line 9 we run the server in port 8000.

So if you understand this:

Congratulations! Your first app has been done! Compile and run the program with cargo run.

You can go to http://127.0.0.1:8000/ or any of the other routes you defined to see the results.