Struct ApiResponse

Source
pub struct ApiResponse<T: Serialize> { /* private fields */ }
Expand description

A generic structure representing a standardized API response.

This struct is designed to encapsulate the result of an API call in a consistent format. It includes fields for the HTTP status code, a human-readable message, and optional data. The use of generics allows this structure to be flexible and work with any type that implements the Serialize trait, making it suitable for JSON serialization (e.g., using serde).

§Type Parameters

  • T: The type of the data field. It must implement the Serialize trait to ensure compatibility with serialization libraries like serde.

§Fields

  • status: u16
    Represents the HTTP status code of the response (e.g., 200 for success, 404 for not found). This provides a machine-readable indicator of the response outcome.

  • message: String
    A human-readable description of the response. This can be used to provide additional context or details about the result (e.g., “Resource created successfully” or “Invalid input”).

  • data: Option<T>
    Contains the payload of the response, if any. The use of Option allows this field to be omitted when there is no data to return (e.g., in case of an error). The type T is generic, enabling flexibility for different kinds of data (e.g., user information, list of items, etc.).

§Example

use serde::Serialize;

#[derive(Serialize)]
struct User {
    id: u32,
    name: String,
}

let response = ApiResponse {
    status: 0,
    message: "User retrieved successfully".to_string(),
    data: Some(User {
        id: 1,
        name: "Alice".to_string(),
    }),
};

// Serialize the response to JSON
let json_response = serde_json::to_string(&response).unwrap();
println!("{}", json_response);

Implementations§

Source§

impl<T: Serialize> ApiResponse<T>

Source

pub fn new(status: u16, message: String, data: T) -> Self

Source

pub fn get_status(&self) -> u16

Source

pub fn get_message(&self) -> &str

Source

pub fn get_data(&self) -> Option<&T>

Source

pub fn set_status(self, status_code: u16) -> ApiResponse<T>

Source

pub fn set_message(self, message: impl Into<String>) -> ApiResponse<T>

Source

pub fn set_data(self, data: T) -> ApiResponse<T>

Source§

impl<T: Serialize> ApiResponse<T>

Source

pub fn ok(data: T) -> ApiResponse<T>

Source

pub fn fail(data: T) -> ApiResponse<T>

Source

pub fn empty() -> ApiResponse<T>

Trait Implementations§

Source§

impl<T: Debug + Serialize> Debug for ApiResponse<T>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<T> IntoResponse for ApiResponse<T>
where T: Serialize,

Source§

fn into_response(self) -> Response

Create a response.
Source§

impl<T> Serialize for ApiResponse<T>
where T: Serialize + Serialize,

Source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. Read more

Auto Trait Implementations§

§

impl<T> Freeze for ApiResponse<T>
where T: Freeze,

§

impl<T> RefUnwindSafe for ApiResponse<T>
where T: RefUnwindSafe,

§

impl<T> Send for ApiResponse<T>
where T: Send,

§

impl<T> Sync for ApiResponse<T>
where T: Sync,

§

impl<T> Unpin for ApiResponse<T>
where T: Unpin,

§

impl<T> UnwindSafe for ApiResponse<T>
where T: UnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.