Introduction
custom structured responses
Common Response Types in Rust
Result
Option
HttpResponse (Web APIs)
impl Responder
ServiceResponse
Custom struct responses
JSON responses
Objective and MCQ
Introduction
When building backend applications or APIs in Rust, returning the correct response type is very important. A response is the data that the server sends back to the client after processing a request.
Rust provides several ways to return responses depending on the situation. For example, a function may return:
a success response
an error response
optional data
JSON data
custom structured responses
Understanding these response types helps developers build clean, safe, and maintainable Rust applications.
What is a Response in Rust?
A response represents the result of a computation or request. It tells the caller whether the operation:
succeeded
failed
returned data
returned nothing
Rust commonly uses special enums and types to represent responses safely.
Common Response Types in Rust
The most commonly used response types are:
Result<T, E>
Option<T>
HttpResponse (Web APIs)
impl Responder
ServiceResponse
Custom struct responses
JSON responses
Let's understand each with syntax and examples.
Result Response
The Result type is used when an operation may succeed or fail.
Syntax
Result<T, E>
Where:
T = success value
E = error value
Example
fn divide(a: i32, b: i32) -> Result<i32, String> {
if b == 0 {
return Err("Cannot divide by zero".to_string());
}
Ok(a / b)
}
fn main() {
let result = divide(10, 2);
match result {
Ok(value) => println!("Result: {}", value),
Err(e) => println!("Error: {}", e),
}
}
Output
Result: 5
Option Response
Option is used when a value may or may not exist.
Syntax
Option<T>
Possible values:
Some(value)
None
Example
fn find_number(numbers: Vec<i32>, target: i32) -> Option<i32> {
for n in numbers {
if n == target {
return Some(n);
}
}
None
}
fn main() {
let result = find_number(vec![1,2,3,4], 3);
match result {
Some(n) => println!("Found: {}", n),
None => println!("Not found"),
}
}
Output
Found: 3
HttpResponse (Web APIs)
When building APIs using Actix-Web, responses are created using HttpResponse.
Syntax
HttpResponse::StatusCode().body(data)
Example
use actix_web::{HttpResponse};
fn success_response() -> HttpResponse {
HttpResponse::Ok().body("Request successful")
}
Output
Status: 200 OK
Body: Request successful
JSON Response
Most APIs return JSON responses.
Syntax
HttpResponse::Ok().json(data)
Example
use actix_web::HttpResponse;
use serde::Serialize;
#[derive(Serialize)]
struct User {
name: String,
age: u8
}
fn user_response() -> HttpResponse {
let user = User {
name: "Ashwani".to_string(),
age: 30
};
HttpResponse::Ok().json(user)
}
Example JSON Output
{
"name": "Ashwani",
"age": 30
}
impl Responder
Rust frameworks allow returning any type that implements Responder.
Syntax
async fn handler() -> impl Responder
Example
use actix_web::{Responder, HttpResponse};
async fn hello() -> impl Responder {
HttpResponse::Ok().body("Hello Rust")
}
Output
Hello Rust
Custom Struct Response
Sometimes we create structured responses for APIs.
Syntax
struct ApiResponse<T>
Example
use serde::Serialize;
#[derive(Serialize)]
struct ApiResponse<T> {
success: bool,
data: T
}
fn main() {
let response = ApiResponse {
success: true,
data: "User created"
};
println!("Success: {}", response.success);
}
Output
Success: true
ServiceResponse (Middleware Response)
When working with Actix middleware, responses are wrapped inside ServiceResponse.
Syntax
ServiceResponse<B>
Example concept:
ServiceRequest → Middleware → ServiceResponse
Middleware may modify responses before sending them back to the client.
Summary
Objective and MCQ
- What is the most commonly used HTTP response type in Actix-web?
A. ResponseData
B. HttpResponse
C. ServerResponse
D. ApiResponse
✅ Answer: B
HttpResponse is the primary type used to construct HTTP responses in Actix-web.
- Which trait allows Actix handlers to return multiple response types?
A. Display
B. Responder
C. Clone
D. Debug
✅ Answer: B
Handler functions can return any type implementing the Responder trait.
- Which method finalizes a response builder with body content?
A. .finish()
B. .body()
C. .complete()
D. .close()
✅ Answer: B
.body() finalizes the HttpResponseBuilder with response content.
- Which method is used to send JSON data in an Actix response?
A. .json()
B. .data()
C. .serialize()
D. .send_json()
✅ Answer: A
.json() converts a structure to JSON response.
- What does HttpResponse::Ok() represent?
A. HTTP 200 response
B. HTTP 404 response
C. HTTP 500 response
D. HTTP 201 response
✅ Answer: A
Ok() creates a response builder with status code 200.
- Which status code indicates resource creation?
A. 200
B. 201
C. 404
D. 500
✅ Answer: B
HttpResponse::Created() represents status code 201.
- Which HTTP response indicates authentication failure?
A. 200
B. 403
C. 401
D. 302
✅ Answer: C
401 Unauthorized indicates authentication failure.
- Which HTTP response indicates resource not found?
A. 401
B. 404
C. 403
D. 500
✅ Answer: B
404 Not Found is returned when a resource is missing.
- What type is commonly used for JSON responses in Actix?
A. Json
B. Map
C. Data
D. String
✅ Answer: A
Json serializes Rust structures into JSON responses.
- Which response type is used for plain text responses?
A. HttpResponse::Ok().body("text")
B. TextResponse
C. StringResponse
D. PlainResponse
✅ Answer: A
- What does ServiceResponse represent?
A. Only HTTP body
B. HTTP request + response wrapper
C. Only HTTP headers
D. Only status code
✅ Answer: B
ServiceResponse wraps both the request and response objects.
- Why are generics used in ServiceResponse?
A. To support multiple body types
B. To increase performance only
C. To store database values
D. To reduce memory usage
✅ Answer: A
Generic B allows different body types in responses.
- Which body type trait must response bodies implement?
A. Future
B. MessageBody
C. Serialize
D. BodyTrait
✅ Answer: B
Actix requires response body types to implement MessageBody.
- Which type allows returning two possible response body types?
A. DualBody
B. EitherBody
C. OptionalBody
D. VariantBody
✅ Answer: B
EitherBody allows two alternative body types.
- Why is EitherBody useful in middleware?
A. To reduce memory usage
B. To return either middleware response or inner service response
C. To store request data
D. To parse JSON
✅ Answer: B
Middleware may return either its own response or the inner service response.
- Which method converts body to a boxed type?
A. box_body()
B. map_into_boxed_body()
C. convert_body()
D. wrap_body()
✅ Answer: B
This converts the response body into BoxBody.
- Which method changes the response body using a closure?
A. map_response()
B. map_body()
C. convert_body()
D. update_body()
✅ Answer: B
map_body() transforms the response body type.
- What is the purpose of HTTP response headers?
A. Store database values
B. Provide metadata about the response
C. Control server execution
D. Encrypt responses
✅ Answer: B
- Which HTTP response indicates a server error?
A. 404
B. 403
C. 500
D. 201
✅ Answer: C
500 Internal Server Error indicates server failure.
- Why are different response types used in Rust web APIs?
A. To support various content formats and HTTP statuses
B. To reduce Rust compilation time
C. To remove middleware
D. To simplify database queries
✅ Answer: A
Different response types allow APIs to return JSON, text, HTML, or error responses depending on the situation.
Top comments (0)