Skip to main content

ollama_sdk/types/
http.rs

1use crate::Result;
2use bytes::Bytes;
3use serde::Serialize;
4
5/// Represents a generic HTTP request.
6///
7/// This struct is used internally by the transport layer to construct
8/// and send requests.
9#[derive(Default, Debug)]
10pub struct HttpRequest {
11    /// The URL path of the API endpoint (e.g., "/api/chat").
12    pub url: String,
13    /// The HTTP verb (GET, POST, PUT, DELETE) for the request.
14    pub verb: HttpVerb,
15    /// The optional request body, serialized as a JSON value.
16    pub body: Option<serde_json::Value>,
17}
18
19/// Represents the HTTP verbs supported for requests.
20#[derive(Default, Debug)]
21pub enum HttpVerb {
22    /// HTTP GET method.
23    #[default]
24    GET,
25    /// HTTP POST method.
26    POST,
27    /// HTTP PUT method.
28    PUT,
29    /// HTTP DELETE method.
30    DELETE,
31}
32
33/// Represents a generic HTTP response.
34///
35/// This struct contains the raw bytes of the response body.
36#[derive(Debug)]
37pub struct HttpResponse {
38    /// The optional body of the HTTP response.
39    pub body: Option<Bytes>,
40}
41
42impl HttpRequest {
43    /// Creates a new [`HttpRequest`] with the specified URL path.
44    ///
45    /// The default HTTP verb is [`HttpVerb::GET`].
46    pub fn new(url: impl Into<String>) -> Self {
47        Self {
48            url: url.into(),
49            ..Default::default()
50        }
51    }
52
53    /// Sets the HTTP verb for the request to [`HttpVerb::GET`].
54    pub fn get(mut self) -> Self {
55        self.verb = HttpVerb::GET;
56        self
57    }
58
59    /// Sets the HTTP verb for the request to [`HttpVerb::POST`].
60    pub fn post(mut self) -> Self {
61        self.verb = HttpVerb::POST;
62        self
63    }
64
65    /// Sets the HTTP verb for the request to [`HttpVerb::PUT`].
66    pub fn put(mut self) -> Self {
67        self.verb = HttpVerb::PUT;
68        self
69    }
70
71    /// Sets the HTTP verb for the request to [`HttpVerb::DELETE`].
72    pub fn delete(mut self) -> Self {
73        self.verb = HttpVerb::DELETE;
74        self
75    }
76
77    /// Sets the request body by serializing the given `T` into a JSON value.
78    ///
79    /// # Arguments
80    ///
81    /// * `body` - The data structure to be serialized as the request body.
82    ///
83    /// # Errors
84    ///
85    /// Returns an [`Error::JsonParse`](variant@crate::Error::JsonParse) if the
86    /// `body` cannot be serialized to JSON.
87    pub fn body<T: Serialize>(mut self, body: T) -> Result<Self> {
88        self.body = Some(serde_json::to_value(body)?);
89        Ok(self)
90    }
91}