openrouter_rs/api/
api_keys.rs

1use std::collections::HashMap;
2
3use serde::{Deserialize, Serialize};
4use surf::http::headers::AUTHORIZATION;
5
6use crate::{error::OpenRouterError, types::ApiResponse, utils::handle_error};
7
8#[derive(Serialize, Deserialize, Debug)]
9pub struct ApiKey {
10    pub name: Option<String>,
11    pub label: Option<String>,
12    pub limit: Option<f64>,
13    pub disabled: Option<bool>,
14    pub created_at: Option<String>,
15    pub updated_at: Option<String>,
16    pub hash: Option<String>,
17    pub key: Option<String>,
18}
19
20#[derive(Serialize, Deserialize, Debug)]
21pub struct ApiKeyDetails {
22    pub label: String,
23    pub usage: f64,
24    pub is_free_tier: bool,
25    pub is_provisioning_key: bool,
26    pub rate_limit: RateLimit,
27    pub limit: Option<f64>,
28    pub limit_remaining: Option<f64>,
29}
30
31#[derive(Serialize, Deserialize, Debug)]
32pub struct RateLimit {
33    pub requests: f64,
34    pub interval: String,
35}
36
37#[derive(Serialize)]
38struct CreateApiKeyRequest {
39    name: String,
40    limit: Option<f64>,
41}
42
43#[derive(Serialize)]
44struct UpdateApiKeyRequest {
45    name: Option<String>,
46    disabled: Option<bool>,
47    limit: Option<f64>,
48}
49
50/// Get information on the API key associated with the current authentication session
51///
52/// # Arguments
53///
54/// * `base_url` - The base URL of the OpenRouter API.
55/// * `api_key` - The API key for authentication.
56///
57/// # Returns
58///
59/// * `Result<ApiKeyDetails, OpenRouterError>` - The details of the current API key.
60pub async fn get_current_api_key(
61    base_url: &str,
62    api_key: &str,
63) -> Result<ApiKeyDetails, OpenRouterError> {
64    let url = format!("{base_url}/key");
65
66    let mut response = surf::get(url)
67        .header(AUTHORIZATION, format!("Bearer {api_key}"))
68        .send()
69        .await?;
70
71    if response.status().is_success() {
72        let api_response: ApiResponse<_> = response.body_json().await?;
73        Ok(api_response.data)
74    } else {
75        handle_error(response).await?;
76        unreachable!()
77    }
78}
79
80/// Returns a list of all API keys associated with the account. Requires a Provisioning API key.
81///
82/// # Arguments
83///
84/// * `base_url` - The base URL of the OpenRouter API.
85/// * `api_key` - The API key for authentication.
86/// * `offset` - Optional offset for the API keys.
87/// * `include_disabled` - Optional flag to include disabled API keys.
88///
89/// # Returns
90///
91/// * `Result<Vec<ApiKey>, OpenRouterError>` - A list of API keys.
92pub async fn list_api_keys(
93    base_url: &str,
94    api_key: &str,
95    offset: Option<f64>,
96    include_disabled: Option<bool>,
97) -> Result<Vec<ApiKey>, OpenRouterError> {
98    let url = format!("{base_url}/keys");
99    let mut query_params = HashMap::new();
100    if let Some(offset) = offset {
101        query_params.insert("offset", offset.to_string());
102    }
103    if let Some(include_disabled) = include_disabled {
104        query_params.insert("include_disabled", include_disabled.to_string());
105    }
106
107    let mut response = surf::get(url)
108        .header(AUTHORIZATION, format!("Bearer {api_key}"))
109        .query(&query_params)?
110        .await?;
111
112    if response.status().is_success() {
113        let api_response: ApiResponse<_> = response.body_json().await?;
114        Ok(api_response.data)
115    } else {
116        handle_error(response).await?;
117        unreachable!()
118    }
119}
120
121/// Creates a new API key. Requires a Provisioning API key.
122///
123/// # Arguments
124///
125/// * `base_url` - The base URL of the OpenRouter API.
126/// * `api_key` - The API key for authentication.
127/// * `name` - The display name for the new API key.
128/// * `limit` - Optional credit limit for the new API key.
129///
130/// # Returns
131///
132/// * `Result<ApiKey, OpenRouterError>` - The created API key.
133pub async fn create_api_key(
134    base_url: &str,
135    api_key: &str,
136    name: &str,
137    limit: Option<f64>,
138) -> Result<ApiKey, OpenRouterError> {
139    let url = format!("{base_url}/keys");
140    let request = CreateApiKeyRequest {
141        name: name.to_string(),
142        limit,
143    };
144
145    let mut response = surf::post(url)
146        .header(AUTHORIZATION, format!("Bearer {api_key}"))
147        .body_json(&request)?
148        .await?;
149
150    if response.status().is_success() {
151        let api_response: ApiResponse<_> = response.body_json().await?;
152        Ok(api_response.data)
153    } else {
154        handle_error(response).await?;
155        unreachable!()
156    }
157}
158
159/// Returns details about a specific API key. Requires a Provisioning API key.
160///
161/// # Arguments
162///
163/// * `base_url` - The base URL of the OpenRouter API.
164/// * `api_key` - The API key for authentication.
165/// * `hash` - The hash of the API key to retrieve.
166///
167/// # Returns
168///
169/// * `Result<ApiKey, OpenRouterError>` - The details of the specified API key.
170pub async fn get_api_key(
171    base_url: &str,
172    api_key: &str,
173    hash: &str,
174) -> Result<ApiKey, OpenRouterError> {
175    let url = format!("{base_url}/keys/{hash}");
176
177    let mut response = surf::get(&url)
178        .header(AUTHORIZATION, format!("Bearer {api_key}"))
179        .await?;
180
181    if response.status().is_success() {
182        let api_response: ApiResponse<_> = response.body_json().await?;
183        Ok(api_response.data)
184    } else {
185        handle_error(response).await?;
186        unreachable!()
187    }
188}
189
190/// Deletes an API key. Requires a Provisioning API key.
191///
192/// # Arguments
193///
194/// * `base_url` - The base URL of the OpenRouter API.
195/// * `api_key` - The API key for authentication.
196/// * `hash` - The hash of the API key to delete.
197///
198/// # Returns
199///
200/// * `Result<bool, OpenRouterError>` - A boolean indicating whether the deletion was successful.
201pub async fn delete_api_key(
202    base_url: &str,
203    api_key: &str,
204    hash: &str,
205) -> Result<bool, OpenRouterError> {
206    let url = format!("{base_url}/api/v1/keys/{hash}");
207
208    let response = surf::delete(&url)
209        .header(AUTHORIZATION, format!("Bearer {api_key}"))
210        .await?;
211
212    if response.status().is_success() {
213        Ok(true)
214    } else {
215        handle_error(response).await?;
216        unreachable!()
217    }
218}
219
220/// Updates an existing API key. Requires a Provisioning API key.
221///
222/// # Arguments
223///
224/// * `base_url` - The base URL of the OpenRouter API.
225/// * `api_key` - The API key for authentication.
226/// * `hash` - The hash of the API key to update.
227/// * `name` - Optional new display name for the API key.
228/// * `disabled` - Optional flag to disable the API key.
229/// * `limit` - Optional new credit limit for the API key.
230///
231/// # Returns
232///
233/// * `Result<ApiKey, OpenRouterError>` - The updated API key.
234pub async fn update_api_key(
235    base_url: &str,
236    api_key: &str,
237    hash: &str,
238    name: Option<String>,
239    disabled: Option<bool>,
240    limit: Option<f64>,
241) -> Result<ApiKey, OpenRouterError> {
242    let url = format!("{base_url}/keys/{hash}");
243    let request = UpdateApiKeyRequest {
244        name,
245        disabled,
246        limit,
247    };
248
249    let mut response = surf::patch(&url)
250        .header(AUTHORIZATION, format!("Bearer {api_key}"))
251        .body_json(&request)?
252        .await?;
253
254    if response.status().is_success() {
255        let api_response: ApiResponse<_> = response.body_json().await?;
256        Ok(api_response.data)
257    } else {
258        handle_error(response).await?;
259        unreachable!()
260    }
261}