DEV Community

Cover image for Build Your First API with Rust
Nathan
Nathan

Posted on • Edited on

Build Your First API with Rust

Rust is a popular programming language( as you know I wrote several articles about it) , but for beginners it may be difficult to discover projects for it or even have a strong understanding of it.
Building something useful is a fantastic approach to get started with any language.

I often thought about the fact that Rust can be a powerful API back-end some reasons include:
-Rust is a very fast language and can handle a lot of concurrent requests.
-Rust is very reliable and there are rarely any crashes.

So I searched a framework to build API , I found rocket , there are a lot of tutorial about building an API with Rocket connected to a database but there are a little more complex for someone that just begin with Rust.

Build a simple REST API — A Step-by-Step.

We are going to build a simple crypto price API. For that, we are going to use the Rocket framework, and "Reqwest" to send HTTP request into our back-end API. This is the following step to follow:

  • Start a web server .
  • Listen to requests .
  • If a request comes in, look at the Path in the HTTP header.
  • Send a request to the backend API with reqwest. -Send the response back to the sender.

Installing Rust Nightly

We must install nightly because Rocket makes extensive use of Rust's syntax extensions and other advanced, unstable features.

rustup default nightly

Create a new project cargo new SimpleAPI .

Dependencies


[dependencies]
rocket = "0.4.11"
rocket_codegen = "0.4.4"
http = "0.2"
reqwest = { version = "0.11", features = ["blocking"] }

What is Rocket

Rocket is a web framework for Rust that makes it simple to write fast web applications without sacrificing flexibility or type safety.

Rocket aims to make web development fast, simple, and secure. It does this through its unique design, which focuses on stateless request handling, composable middleware, and a declarative approach to route matching.

This design makes Rocket incredibly easy to use and understand. It's also easy to extend and customize for your own needs.
We want to create an landing page, with little info about this API.

Image description

For this we will create the first route, we do use a special macro before the endpoint function. This macro describes the route's method and its path.
The method return a reference to a 'str'.

#[get("/")]
fn index() -> &'static str {
    "Navigate to http://localhost:8000/check/<type your Coin> to check  details about this crypto  !"
}

Enter fullscreen mode Exit fullscreen mode

The second route is also listen for a GET request,The full path for this endpoint is : "/check/coin" where coin is the user input.This time will fetch to another API to get price for the current crypto.
The "check" function receive the parameter "coin" as parameter which is a sort of string, then the function return a "Result". According to the Rust lang book:

Result is the type used for returning and propagating errors. It is an enum with the variants, Ok(T), representing success and containing a value, and Err(E), representing error and containing an error value.

For the body of the function we will use "reqwest" to send HTTP request with Rust.

The reqwest crate provides a convenient, higher-level HTTP Client.It handles many of the things that most people just expect an HTTP client to do for them.
In the documentation they said that "reqwest::blocking" is more convenient for application that make only few HTTP Requests.

Firstly we do a string format with the chosen coin and the URL of coingecko API, after it we send the request and whether it fail or not we will return "Ok" which representing success.
If the response is successful, we send back the response to the sender : Ok(format!("{} ", resp.text().unwrap()))

#[get("/check/<coin>")]
fn check(coin: &RawStr) -> Result<String, Box<dyn std::error::Error>> {
    let request_url =format!("https://api.coingecko.com/api/v3/coins/{}", coin);
    println!("{}", request_url);
    let resp = reqwest::blocking::get(request_url)?;
    if resp.status().is_success(){

        `Ok(format!("{} ", resp.text().unwrap()))`
    }
    else{
        let response = resp.text().unwrap();
        Ok(format!("{} is not a coin!", response))
    }
}
Enter fullscreen mode Exit fullscreen mode

The last function is the "Main", it mounts all the routes at the / path ( notice it take the function name and not the route path) , and launches the application.

fn main() {
    rocket::ignite().mount("/", routes![index, check]).launch();
}

Enter fullscreen mode Exit fullscreen mode

Compile and run the program with cargo run. You should see the following:

Image description

Finally the result looks like :
Image description

I know! We received only a big JSON Data and the price is not parsed. In the next article I will explain how to work with JSON and we will use more functionality of "Reqwest" framework.

In the case you don't know we've just launched, check us at www.blstsecurity.com ;)

Join our Discord Server we talk about Rust and API: https://discord.gg/3ThF8NYd

Top comments (0)