Rust, Software Development

Send HTTP Responses From Actix-Web

Learning how to send HTTP responses from Actix-web to clients will help us craft the responses according to our needs. For instance, we could send JSON responses for specific URIs. Although we could just set the response content type and send text contents, some use-cases require sending bytes instead.

Cargo.toml

We have these dependencies, and we are using Rust 1.44.0.

Send HTTP Body Response – HTML, XML, JSON

To send an HTTP response with HTML body from Actix-Web, we need to set the Content-Type to text/html with HTML codes.

The request handler generates the following output.

In the same token, we set the Content-Type accordingly for JSON and XML.

For XML

For XML, we use application/xml.

The codes return the following response to the browser.

For JSON

For JSON, we use application/json.

Actix-Web HTTP Response with JSON via Content-Type

Alternatively, we can use Serde to generate JSON from struct instances automatically.

The browser will display the following.

Actix-Web HTTP Response with JSON via Serde

Any File Using Actix-Web NamedFile

We can send the content of any file as part of the response in Actix-web using NamedFile. NameFile comes with the Actix-file crate, for example.

Send File As Bytes in HTTP Responses

Sometimes a file’s content is stored in a database as a blob data. In such a case, we only bytes data in memory. We could either first write the data to a file and use NamedFile or send them as bytes.

When we access the URL, we would get the following.

The Complete Rust Codes

The followings are the imports.

We need a struct to work with Serde to convert an instance to a JSON automatically.

Then, we have the request handlers.

Lastly, we have the main function.

Loading

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