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