Rust, Software Development

Rust – How to Return JSON Responses from Actix-web

Rust selection sort EPCIS 1.2 XML Actix-web json response

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 [crayon-60ce13dcc6e9f621286673-i/] 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 that represents a list of struct Country.

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 simple and 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.

You Might Also Like