How to call a function from another file and fetch in web

I'm new to Rust and still I am learning things. There is a rust application with main.rs and routes.rs. main.rs file has server configuration and routes.rs has methods with paths.

main.rs

#[macro_use]
extern crate log;

use actix_web::{App, HttpServer};
use dotenv::dotenv;
use listenfd::ListenFd;
use std::env;

mod search;

#[actix_rt::main]
async fn main() -> std::io::Result<()> {
    dotenv().ok();
    env_logger::init();

    let mut listenfd = ListenFd::from_env();
    let mut server = HttpServer::new(|| 
        App::new()
            .configure(search::init_routes)
    );

    server = match listenfd.take_tcp_listener(0)? {
        Some(listener) => server.listen(listener)?,
        None => {
            let host = env::var("HOST").expect("Host not set");
            let port = env::var("PORT").expect("Port not set");
            server.bind(format!("{}:{}", host, port))?
        }
    };

    info!("Starting server");
    server.run().await
}

routes.rs

use crate::search::User;
use actix_web::{get, post, put, delete, web, HttpResponse, Responder};
use serde_json::json;
extern crate reqwest;
extern crate serde;
use reqwest::Error;
use serde::{Deserialize};
use rocket_contrib::json::Json;
use serde_json::Value;
// mod bargainfindermax;

#[get("/users")]
async fn find_all() -> impl Responder {
    HttpResponse::Ok().json(
        vec![
            User { id: 1, email: "tore@cloudmaker.dev".to_string() },
            User { id: 2, email: "tore@cloudmaker.dev".to_string() },
        ]
    )
}

pub fn init_routes(cfg: &mut web::ServiceConfig) {
    cfg.service(find_all);
}

Now what I want is I want to fetch an API using a method in another separate rs file (fetch_test.rs) and route it in the routes.rs file. Then I want to get the response from a web browser by running that route path(link).

How can I do these things ?? I searched everywhere, but I found nothing helpful. And sometimes I didn't understand some documentations also.

**Update - I used reqwest and did println!. But, How can return this to web view ??

Quote blocks are for quoting something someone else said. Please properly use code blocks:

```
// your code
```
1 Like

You can use the reqwest crate to perform a http request.

@alice I used reqwest and did println!. But, How can return this to web view ??

You do not need to @ me for me to be notified :slight_smile:

Where are you running into trouble with returning it?

okay, Noted.

Thing is I tried to return it. But, then it said I want to add a return type. In this case, I have no idea what to do. I tried couple of return types, but it didnt work. Basically how can I return this API as json to web vie ??.

You probably need an .await somewhere and to make the function async.

In my 3rd rs file, I did like this.

extern crate reqwest;

pub fn test_func() {
    let res = reqwest::get("http://api.github.com/users")
.expect("Couldnt")
.text().expect("no res");

let serialized = serde_json::to_string(&res).unwrap();

//println!("{}", res);

return res;
}

Now it says,

mismatched types
expected (), found struct std::string::Stringrustc(E0308)
bfm.rs(12, 8): expected (), found struct std::string::String

And in routes.rs I did this.

#[get("/book")]
async fn test_func() -> impl Responder {
// fn test_func() -> Json<Value> {
    bfm::test_func();
}

the trait bound (): actix_web::responder::Responder is not satisfied
the trait actix_web::responder::Responder is not implemented for ()
note: the return type of a function must have a statically known sizerustc(E0277)
routes.rs(20, 25): the trait actix_web::responder::Responder is not implemented for ()

You need to specify the return type to return something. Consider taking a look at the chapter on functions in the rust book. Additionally you need to return a Responder from your test_func, although i'm not quite sure what that is as I have not used actix web.

If I need to return string or json, what should I use in rust ?? I still have a confusion about this return type thing in rust..

Well if you want to return a string, you can use String.

1 Like

I didnt understand this. Please can u explain ??

When your function has -> Something, you have to return a value of that type.

Yh, I did this now..

extern crate reqwest;

pub fn test_func() -> String {
    let res = reqwest::get("http://api.github.com/users")
.expect("Couldnt")
.text().expect("no res");

let serialized = serde_json::to_string(&res).unwrap();
//println!("{}", res);
return res;
}

How can I get the response from routes.rs file ??

You call it.

let your_string = crate::module_name::test_func();
1 Like

Yes, its working now. It means what I missed was return type. Thank you for your help.

And also How can I send headers with API request ??

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.