Software Development

Rust – How to Return JSON Responses from Actix-web

This post briefly demonstrates how to return JSON response from a web application written using actix-web.


These are things used in the post.

Create a new Rust 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

Modify the cargo.toml to include two dependencies – actix-web and serde.

To server JSON contents, we use web::Json()  from actix-web .

First, we use we import the libraries we need.

Then, we create the struct to represent a country.

Then, we create an HTTP  request handle for HTTP GET  /countries.

Lastly, we implement the main()  function.

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


You Might Also Like