unirate_axum/lib.rs
1//! # unirate-axum
2//!
3//! [Axum](https://docs.rs/axum) integration for the
4//! [UniRate API](https://unirateapi.com) — free, real-time currency exchange
5//! rates, conversion, and VAT rates.
6//!
7//! This crate exposes a ready-made [`router`] that mounts four `GET` routes on
8//! top of the official [`unirate_api::Client`]:
9//!
10//! | Route | Query params | Backing client call |
11//! |---------------|-------------------------|-------------------------------------------|
12//! | `/rate` | `from`, `to` | [`Client::get_rate`] / [`Client::get_all_rates`] |
13//! | `/convert` | `from`, `to`, `amount` | [`Client::convert`] |
14//! | `/currencies` | — | [`Client::get_supported_currencies`] |
15//! | `/vat` | `country` (optional) | [`Client::get_vat_rate`] / [`Client::get_vat_rates`] |
16//!
17//! UniRate errors are mapped to the matching HTTP status with a JSON error
18//! body via [`ApiError`].
19//!
20//! ## Client sourcing
21//!
22//! The UniRate HTTP client itself is **not** re-implemented here — this crate
23//! depends on the published [`unirate-api`](https://crates.io/crates/unirate-api)
24//! crate (`unirate_api::Client`) and only adds the Axum wiring. That keeps the
25//! client parity in one place and this crate small.
26//!
27//! ## Quick start
28//!
29//! ```no_run
30//! use unirate_axum::router;
31//! use unirate_api::Client;
32//!
33//! #[tokio::main]
34//! async fn main() {
35//! let client = Client::new(std::env::var("UNIRATE_API_KEY").unwrap());
36//! let app = router(client);
37//!
38//! let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
39//! axum::serve(listener, app).await.unwrap();
40//! }
41//! ```
42//!
43//! ## Composing into a larger app
44//!
45//! [`router`] returns a plain [`axum::Router`], so you can nest it under a
46//! prefix or merge it into an existing router:
47//!
48//! ```no_run
49//! use axum::Router;
50//! use unirate_axum::router;
51//! use unirate_api::Client;
52//!
53//! let client = Client::new("your-api-key");
54//! let app: Router = Router::new().nest("/currency", router(client));
55//! ```
56
57#![deny(missing_debug_implementations)]
58#![warn(rust_2018_idioms)]
59
60use std::collections::HashMap;
61
62use axum::{
63 extract::{Query, State},
64 http::StatusCode,
65 response::{IntoResponse, Response},
66 routing::get,
67 Json, Router,
68};
69use serde::{Deserialize, Serialize};
70use serde_json::json;
71use unirate_api::{Client, UniRateError, VatRate, VatRateResponse, VatRatesResponse};
72
73/// Build an [`axum::Router`] wired to the given [`Client`].
74///
75/// The client is stored as router [`State`], so every request shares one
76/// connection-pooled [`unirate_api::Client`]. Mount the returned router
77/// directly with [`axum::serve`] or nest it under a prefix.
78///
79/// Routes:
80/// - `GET /rate?from=USD&to=EUR` — single rate. Omit `to` to get every rate
81/// for `from` as a `{ "rates": { .. } }` map.
82/// - `GET /convert?from=USD&to=EUR&amount=100` — converted amount.
83/// - `GET /currencies` — list of supported currency codes.
84/// - `GET /vat?country=DE` — VAT for one country. Omit `country` for all.
85pub fn router(client: Client) -> Router {
86 Router::new()
87 .route("/rate", get(rate_handler))
88 .route("/convert", get(convert_handler))
89 .route("/currencies", get(currencies_handler))
90 .route("/vat", get(vat_handler))
91 .with_state(client)
92}
93
94// ---------------------------------------------------------------------------
95// Query param types
96// ---------------------------------------------------------------------------
97
98/// Query params for `GET /rate`.
99#[derive(Debug, Deserialize)]
100pub struct RateParams {
101 /// Base currency. Defaults to `USD` when omitted.
102 #[serde(default = "default_usd")]
103 pub from: String,
104 /// Target currency. When omitted, all rates for `from` are returned.
105 #[serde(default)]
106 pub to: Option<String>,
107}
108
109/// Query params for `GET /convert`.
110#[derive(Debug, Deserialize)]
111pub struct ConvertParams {
112 /// Source currency. Defaults to `USD` when omitted.
113 #[serde(default = "default_usd")]
114 pub from: String,
115 /// Target currency (required).
116 pub to: String,
117 /// Amount to convert. Defaults to `1`.
118 #[serde(default = "default_amount")]
119 pub amount: f64,
120}
121
122/// Query params for `GET /vat`.
123#[derive(Debug, Deserialize)]
124pub struct VatParams {
125 /// ISO-3166 alpha-2 country code. When omitted, all countries are returned.
126 #[serde(default)]
127 pub country: Option<String>,
128}
129
130fn default_usd() -> String {
131 "USD".to_string()
132}
133
134fn default_amount() -> f64 {
135 1.0
136}
137
138// ---------------------------------------------------------------------------
139// Handlers
140// ---------------------------------------------------------------------------
141
142async fn rate_handler(
143 State(client): State<Client>,
144 Query(params): Query<RateParams>,
145) -> Result<Response, ApiError> {
146 match params.to {
147 Some(to) => {
148 let rate = client.get_rate(¶ms.from, &to).await?;
149 Ok(Json(json!({ "from": params.from.to_uppercase(), "to": to.to_uppercase(), "rate": rate })).into_response())
150 }
151 None => {
152 let rates: HashMap<String, f64> = client.get_all_rates(¶ms.from).await?;
153 Ok(Json(json!({ "from": params.from.to_uppercase(), "rates": rates })).into_response())
154 }
155 }
156}
157
158async fn convert_handler(
159 State(client): State<Client>,
160 Query(params): Query<ConvertParams>,
161) -> Result<Json<ConvertResponse>, ApiError> {
162 let result = client
163 .convert(params.amount, ¶ms.from, ¶ms.to)
164 .await?;
165 Ok(Json(ConvertResponse {
166 from: params.from.to_uppercase(),
167 to: params.to.to_uppercase(),
168 amount: params.amount,
169 result,
170 }))
171}
172
173async fn currencies_handler(
174 State(client): State<Client>,
175) -> Result<Json<CurrenciesResponse>, ApiError> {
176 let currencies = client.get_supported_currencies().await?;
177 Ok(Json(CurrenciesResponse { currencies }))
178}
179
180async fn vat_handler(
181 State(client): State<Client>,
182 Query(params): Query<VatParams>,
183) -> Result<Response, ApiError> {
184 match params.country {
185 Some(country) => {
186 let resp = client.get_vat_rate(&country).await?;
187 Ok(Json(VatCountry::from(resp)).into_response())
188 }
189 None => {
190 let resp = client.get_vat_rates().await?;
191 Ok(Json(VatAll::from(resp)).into_response())
192 }
193 }
194}
195
196// ---------------------------------------------------------------------------
197// Response bodies
198// ---------------------------------------------------------------------------
199
200/// Body of a successful `GET /convert`.
201#[derive(Debug, Serialize)]
202pub struct ConvertResponse {
203 /// Source currency (uppercased).
204 pub from: String,
205 /// Target currency (uppercased).
206 pub to: String,
207 /// The input amount.
208 pub amount: f64,
209 /// The converted amount.
210 pub result: f64,
211}
212
213/// Body of a successful `GET /currencies`.
214#[derive(Debug, Serialize)]
215pub struct CurrenciesResponse {
216 /// Supported currency codes.
217 pub currencies: Vec<String>,
218}
219
220/// VAT rate for a single country, as returned in a JSON response.
221///
222/// The `unirate-api` [`VatRate`] type only derives `Deserialize`, so this
223/// serializable mirror is used for the outgoing HTTP body.
224#[derive(Debug, Serialize)]
225pub struct VatRateBody {
226 /// ISO-3166 alpha-2 country code, when supplied by the upstream API.
227 #[serde(skip_serializing_if = "Option::is_none")]
228 pub country_code: Option<String>,
229 /// Human-readable country name, when supplied.
230 #[serde(skip_serializing_if = "Option::is_none")]
231 pub country_name: Option<String>,
232 /// VAT rate as a percentage (e.g. `19.0`).
233 pub vat_rate: f64,
234}
235
236impl From<VatRate> for VatRateBody {
237 fn from(v: VatRate) -> Self {
238 VatRateBody {
239 country_code: v.country_code,
240 country_name: v.country_name,
241 vat_rate: v.vat_rate,
242 }
243 }
244}
245
246/// Body of a successful `GET /vat?country=XX`.
247#[derive(Debug, Serialize)]
248pub struct VatCountry {
249 /// Echoed country code.
250 #[serde(skip_serializing_if = "Option::is_none")]
251 pub country: Option<String>,
252 /// The country's VAT detail.
253 pub vat_data: VatRateBody,
254}
255
256impl From<VatRateResponse> for VatCountry {
257 fn from(r: VatRateResponse) -> Self {
258 VatCountry {
259 country: r.country,
260 vat_data: r.vat_data.into(),
261 }
262 }
263}
264
265/// Body of a successful `GET /vat` (all countries).
266#[derive(Debug, Serialize)]
267pub struct VatAll {
268 /// Snapshot date, when provided.
269 #[serde(skip_serializing_if = "Option::is_none")]
270 pub date: Option<String>,
271 /// Number of countries in the response.
272 pub total_countries: u32,
273 /// Per-country VAT rates keyed by ISO-3166 alpha-2 code.
274 pub vat_rates: HashMap<String, VatRateBody>,
275}
276
277impl From<VatRatesResponse> for VatAll {
278 fn from(r: VatRatesResponse) -> Self {
279 VatAll {
280 date: r.date,
281 total_countries: r.total_countries,
282 vat_rates: r
283 .vat_rates
284 .into_iter()
285 .map(|(k, v)| (k, v.into()))
286 .collect(),
287 }
288 }
289}
290
291// ---------------------------------------------------------------------------
292// Error mapping
293// ---------------------------------------------------------------------------
294
295/// Wraps a [`UniRateError`] and turns it into an HTTP response.
296///
297/// The status code follows the UniRate error → HTTP mapping:
298///
299/// | UniRate error | HTTP status |
300/// |----------------------------------|-------------|
301/// | `InvalidDate` | 400 Bad Request |
302/// | `Authentication` | 401 Unauthorized |
303/// | `Api { status: 403, .. }` | 403 Forbidden (Pro-gated) |
304/// | `InvalidCurrency` | 404 Not Found |
305/// | `RateLimit` | 429 Too Many Requests |
306/// | `Api { status: 503, .. }` | 503 Service Unavailable |
307/// | `Api { status, .. }` (other) | that status (clamped to 5xx-safe) |
308/// | `Http` / `Json` (transport) | 502 Bad Gateway |
309#[derive(Debug)]
310pub struct ApiError(pub UniRateError);
311
312impl From<UniRateError> for ApiError {
313 fn from(err: UniRateError) -> Self {
314 ApiError(err)
315 }
316}
317
318impl std::fmt::Display for ApiError {
319 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
320 self.0.fmt(f)
321 }
322}
323
324impl std::error::Error for ApiError {}
325
326impl IntoResponse for ApiError {
327 fn into_response(self) -> Response {
328 let (status, message) = match &self.0 {
329 UniRateError::InvalidDate => (
330 StatusCode::BAD_REQUEST,
331 "Invalid request parameters".to_string(),
332 ),
333 UniRateError::Authentication => (
334 StatusCode::UNAUTHORIZED,
335 "Missing or invalid API key".to_string(),
336 ),
337 UniRateError::InvalidCurrency => (
338 StatusCode::NOT_FOUND,
339 "Currency not found or no data available".to_string(),
340 ),
341 UniRateError::RateLimit => (
342 StatusCode::TOO_MANY_REQUESTS,
343 "Rate limit exceeded".to_string(),
344 ),
345 UniRateError::Api { status, body } => {
346 let code = StatusCode::from_u16(*status).unwrap_or(StatusCode::BAD_GATEWAY);
347 let message = match *status {
348 403 => "Endpoint requires a Pro subscription".to_string(),
349 503 => "Service unavailable".to_string(),
350 _ if body.is_empty() => format!("Upstream API error (status {status})"),
351 _ => body.clone(),
352 };
353 (code, message)
354 }
355 // Transport / decode failures are our side of the fence — the
356 // upstream call never completed cleanly, so surface a 502.
357 UniRateError::Http(_) | UniRateError::Json(_) => (
358 StatusCode::BAD_GATEWAY,
359 "Failed to reach the UniRate API".to_string(),
360 ),
361 // `UniRateError` is `#[non_exhaustive]`; be defensive.
362 _ => (
363 StatusCode::INTERNAL_SERVER_ERROR,
364 "Unexpected error".to_string(),
365 ),
366 };
367
368 let body = Json(json!({
369 "error": {
370 "status": status.as_u16(),
371 "message": message,
372 }
373 }));
374
375 (status, body).into_response()
376 }
377}