Rust, Software Development

Path Parameter and JSON Payload in Actix-Web

This post demonstrates how to capture path parameters and JSON payload in Actix-web.

Path Parameter And JSON Payload

A path parameter is a type of parameter provided to an application as part of a URI in an HTTP Request. For instance, wherein 1 is a path parameter value and may represent a Post ID. How to extract what from a URI is determined by the application. A JSON payload refers to the JSON content of an HTTP Request Body. When sending JSON, the HTTP Request must specify Content-Type=application/json as one of its headers.

Sample REST API Using Actix-Web

Assuming we have the following URL.

The JSON payload to send to the server using HTTP PUT and the URL.

Rust and Actix-Web Codes

First, we need to update Cargo.toml and put in a dependency Actix-Web.

Next, we need 2 structs. The JSONPayload struct represents the JSON payload. It needs the Deserialize trait so the server codes can automatically deserialize JSON from an HTTP request into a struct instance. Meanwhile, the Response struct represents an empty HTTP response from the server.

Next, we need a request handler to pick up the Path Parameter from the URL and JSON from the HTTP request body. To refer to each, we use web::Path and web::Json types as function parameters.

Finally, we need the main function to start Actix-Web from. Here we map the path /persons/{person_id}  and HTTP PUT to the handle_request function

Test Codes

This is testing with PostMan. First, we set the HTTP headers Accept and Content-Type. Also, we specify the HTTP method PUT and the URL. The URL is localhost:8088/persons/1 where 1 is Person ID.

Next, we set the body to a JSON value.

Then, click the Send button to send the request to the server. When the Actix-Web application received the request, it outputs the following on the console.

Meanwhile, PostMan will receive an empty response.

Tested with Rust 1.37.0.

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