Rust, Software Development

Rust – How to Return JSON Responses from Actix-web

Are you planning to develop an API-only backend using Rust and Actix-web? If so, you need to know how to return JSON responses from Actix-web. This post briefly shows how to create a Rust application using actix-web that returns JSON responses.

Rust Requirements For Actix-Web

These are things used in the post.

Create a new Rust Actix-Web Project

Go to File  -> New  -> Project...  and choose Rust. Then click Next and enter the Project Name and Project Location. Click Finish to complete.

Update Cargo.toml For Actix-Web

Next, modify the cargo.toml to include two dependencies – actix-web and serde. These are the only two dependencies we need for our sample Actix-web application.

Create Rust Codes To Return JSON Response

To server JSON contents, we use web::Json()  from actix-web. First, we use we import the struct and traits we need.

Then, we create the struct to represent a country. Our Rust Actix-web application returns a JSON response representing a struct country list.

Then, we create an HTTP  request handle for HTTP GET  /countries. Note that the function is async.

Lastly, we implement the main()  function. The codes in this function are straightforward.

The codes listen at port 8088  on localhost for HTTP  GET requests to /countries.

Test Actix-Web And JSON Response

Finally, we can test our Rust codes that make Actix-web return a JSON response. For example, go to localhost:8088/countries using a browser, and the application returns a JSON response as follows. The response contains three JSON objects our Actix-web application took from the get_country_list  function.

As we can see, we get a JSON response that contains an array of JSON representing countries. Also, the response header content-type indicates that the response is of type application/json.

BASIC and Bearer Authentications (Optional)

Suppose we want to secure our application, we could use Actix-web BASIC or Bearer authentication.


Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.

You Might Also Like