0

Rust – How to Return JSON Responses from Actix-web

Last Updated on

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

Requirements

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.

main.rs

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 .

Tests

Karl San Gabriel

Karl San Gabriel

Professional Software Developer