cloudflare-api 0.1.0

Typed Rust client bindings for the Cloudflare API generated from OpenAPI definitions.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
use percent_encoding::{NON_ALPHANUMERIC, utf8_percent_encode};
use reqwest::header::{AUTHORIZATION, HeaderMap, HeaderName, HeaderValue};
use reqwest::{Method, RequestBuilder};
use serde_json::{Map, Value};
use std::fmt;
use std::marker::PhantomData;

pub type ResponseValue<T> = T;

#[derive(Debug, Clone)]
pub struct Error<E = ()> {
    message: String,
    _marker: PhantomData<E>,
}

impl<E> Error<E> {
    fn new(message: impl Into<String>) -> Self {
        Self {
            message: message.into(),
            _marker: PhantomData,
        }
    }
}

impl<E> fmt::Display for Error<E> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.message)
    }
}

impl<E: fmt::Debug> std::error::Error for Error<E> {}

#[derive(Clone, Debug)]
pub struct Client {
    reqwest_client: reqwest::Client,
    base_url: String,
    default_headers: HeaderMap,
}

impl Default for Client {
    fn default() -> Self {
        Self::with_default_base_url()
    }
}

impl Client {
    pub fn with_default_base_url() -> Self {
        Self::from_base_url("https://api.cloudflare.com/client/v4")
    }

    pub fn from_base_url(base_url: impl Into<String>) -> Self {
        Self {
            reqwest_client: reqwest::Client::new(),
            base_url: base_url.into(),
            default_headers: HeaderMap::new(),
        }
    }

    pub fn set_bearer_token(
        &mut self,
        token: impl AsRef<str>,
    ) -> Result<(), reqwest::header::InvalidHeaderValue> {
        let value = format!("Bearer {}", token.as_ref());
        self.default_headers
            .insert(AUTHORIZATION, HeaderValue::from_str(&value)?);
        Ok(())
    }

    pub fn set_api_key_auth(
        &mut self,
        email: impl AsRef<str>,
        key: impl AsRef<str>,
    ) -> Result<(), reqwest::header::InvalidHeaderValue> {
        self.default_headers.insert(
            HeaderName::from_static("x-auth-email"),
            HeaderValue::from_str(email.as_ref())?,
        );
        self.default_headers.insert(
            HeaderName::from_static("x-auth-key"),
            HeaderValue::from_str(key.as_ref())?,
        );
        Ok(())
    }

    pub fn set_service_key(
        &mut self,
        key: impl AsRef<str>,
    ) -> Result<(), reqwest::header::InvalidHeaderValue> {
        self.default_headers.insert(
            HeaderName::from_static("x-auth-user-service-key"),
            HeaderValue::from_str(key.as_ref())?,
        );
        Ok(())
    }

    pub fn list_zones(&self) -> ZonesGetBuilder<'_> {
        ZonesGetBuilder {
            client: self,
            account_id: None,
            name: None,
            status: None,
            page: None,
            per_page: None,
        }
    }

    pub fn zone(&self) -> Zones0GetBuilder<'_> {
        Zones0GetBuilder {
            client: self,
            zone_id: None,
        }
    }

    pub fn list_dns_records(&self) -> DnsRecordsForAZoneListDnsRecordsBuilder<'_> {
        DnsRecordsForAZoneListDnsRecordsBuilder {
            client: self,
            zone_id: None,
            name: None,
            page: None,
            per_page: None,
        }
    }

    pub fn create_dns_record(&self) -> DnsRecordsForAZoneCreateDnsRecordBuilder<'_> {
        DnsRecordsForAZoneCreateDnsRecordBuilder {
            client: self,
            zone_id: None,
            body: None,
        }
    }

    pub fn delete_dns_record(&self) -> DnsRecordsForAZoneDeleteDnsRecordBuilder<'_> {
        DnsRecordsForAZoneDeleteDnsRecordBuilder {
            client: self,
            zone_id: None,
            dns_record_id: None,
            body: None,
        }
    }

    pub fn list_worker_routes(&self) -> WorkerRoutesListRoutesBuilder<'_> {
        WorkerRoutesListRoutesBuilder {
            client: self,
            zone_id: None,
        }
    }

    pub fn create_worker_route(&self) -> WorkerRoutesCreateRouteBuilder<'_> {
        WorkerRoutesCreateRouteBuilder {
            client: self,
            zone_id: None,
            body: None,
        }
    }

    pub fn delete_worker_route(&self) -> WorkerRoutesDeleteRouteBuilder<'_> {
        WorkerRoutesDeleteRouteBuilder {
            client: self,
            zone_id: None,
            route_id: None,
            body: None,
        }
    }

    fn endpoint(&self, path: &str) -> String {
        let base = self.base_url.trim_end_matches('/');
        let suffix = path.trim_start_matches('/');
        format!("{base}/{suffix}")
    }

    fn request(&self, method: Method, path: &str) -> RequestBuilder {
        self.reqwest_client
            .request(method, self.endpoint(path))
            .headers(self.default_headers.clone())
    }

    async fn send_json(&self, request: RequestBuilder) -> Result<ResponseValue<Value>, Error<()>> {
        let response = request
            .send()
            .await
            .map_err(|e| Error::new(format!("request failed: {e}")))?;
        let status = response.status();
        if !status.is_success() {
            let body = response
                .text()
                .await
                .unwrap_or_else(|_| "<failed to read response body>".to_string());
            return Err(Error::new(format!(
                "Cloudflare API error (HTTP {}): {}",
                status.as_u16(),
                body
            )));
        }

        response
            .json::<Value>()
            .await
            .map_err(|e| Error::new(format!("invalid JSON response: {e}")))
    }
}

fn encode_path(value: &str) -> String {
    utf8_percent_encode(value, NON_ALPHANUMERIC).to_string()
}

#[derive(Clone, Debug)]
pub struct ZonesGetBuilder<'a> {
    client: &'a Client,
    account_id: Option<String>,
    name: Option<String>,
    status: Option<String>,
    page: Option<u32>,
    per_page: Option<u32>,
}

impl<'a> ZonesGetBuilder<'a> {
    pub fn account_id(mut self, value: impl Into<String>) -> Self {
        self.account_id = Some(value.into());
        self
    }

    pub fn name(mut self, value: impl Into<String>) -> Self {
        self.name = Some(value.into());
        self
    }

    pub fn status(mut self, value: impl Into<String>) -> Self {
        self.status = Some(value.into());
        self
    }

    pub fn page(mut self, value: u32) -> Self {
        self.page = Some(value);
        self
    }

    pub fn per_page(mut self, value: u32) -> Self {
        self.per_page = Some(value);
        self
    }

    pub async fn send(self) -> Result<ResponseValue<Value>, Error<()>> {
        let mut request = self.client.request(Method::GET, "/zones");
        if let Some(account_id) = self.account_id {
            request = request.query(&[("account.id", account_id)]);
        }
        if let Some(name) = self.name {
            request = request.query(&[("name", name)]);
        }
        if let Some(status) = self.status {
            request = request.query(&[("status", status)]);
        }
        if let Some(page) = self.page {
            request = request.query(&[("page", page)]);
        }
        if let Some(per_page) = self.per_page {
            request = request.query(&[("per_page", per_page)]);
        }
        self.client.send_json(request).await
    }
}

#[derive(Clone, Debug)]
pub struct Zones0GetBuilder<'a> {
    client: &'a Client,
    zone_id: Option<String>,
}

impl<'a> Zones0GetBuilder<'a> {
    pub fn zone_id(mut self, value: impl Into<String>) -> Self {
        self.zone_id = Some(value.into());
        self
    }

    pub async fn send(self) -> Result<ResponseValue<Value>, Error<()>> {
        let zone_id = self
            .zone_id
            .ok_or_else(|| Error::new("zone_id is required"))?;
        let path = format!("/zones/{}", encode_path(&zone_id));
        self.client
            .send_json(self.client.request(Method::GET, &path))
            .await
    }
}

#[derive(Clone, Debug)]
pub struct DnsRecordsForAZoneListDnsRecordsBuilder<'a> {
    client: &'a Client,
    zone_id: Option<String>,
    name: Option<String>,
    page: Option<u32>,
    per_page: Option<u32>,
}

impl<'a> DnsRecordsForAZoneListDnsRecordsBuilder<'a> {
    pub fn zone_id(mut self, value: impl Into<String>) -> Self {
        self.zone_id = Some(value.into());
        self
    }

    pub fn name(mut self, value: impl Into<String>) -> Self {
        self.name = Some(value.into());
        self
    }

    pub fn page(mut self, value: u32) -> Self {
        self.page = Some(value);
        self
    }

    pub fn per_page(mut self, value: u32) -> Self {
        self.per_page = Some(value);
        self
    }

    pub async fn send(self) -> Result<ResponseValue<Value>, Error<()>> {
        let zone_id = self
            .zone_id
            .ok_or_else(|| Error::new("zone_id is required"))?;
        let path = format!("/zones/{}/dns_records", encode_path(&zone_id));
        let mut request = self.client.request(Method::GET, &path);
        if let Some(name) = self.name {
            request = request.query(&[("name", name)]);
        }
        if let Some(page) = self.page {
            request = request.query(&[("page", page)]);
        }
        if let Some(per_page) = self.per_page {
            request = request.query(&[("per_page", per_page)]);
        }
        self.client.send_json(request).await
    }
}

#[derive(Clone, Debug)]
pub struct DnsRecordsForAZoneCreateDnsRecordBuilder<'a> {
    client: &'a Client,
    zone_id: Option<String>,
    body: Option<Map<String, Value>>,
}

impl<'a> DnsRecordsForAZoneCreateDnsRecordBuilder<'a> {
    pub fn zone_id(mut self, value: impl Into<String>) -> Self {
        self.zone_id = Some(value.into());
        self
    }

    pub fn body(mut self, body: Map<String, Value>) -> Self {
        self.body = Some(body);
        self
    }

    pub async fn send(self) -> Result<ResponseValue<Value>, Error<()>> {
        let zone_id = self
            .zone_id
            .ok_or_else(|| Error::new("zone_id is required"))?;
        let body = self.body.unwrap_or_default();
        let path = format!("/zones/{}/dns_records", encode_path(&zone_id));
        self.client
            .send_json(self.client.request(Method::POST, &path).json(&body))
            .await
    }
}

#[derive(Clone, Debug)]
pub struct DnsRecordsForAZoneDeleteDnsRecordBuilder<'a> {
    client: &'a Client,
    zone_id: Option<String>,
    dns_record_id: Option<String>,
    body: Option<Map<String, Value>>,
}

impl<'a> DnsRecordsForAZoneDeleteDnsRecordBuilder<'a> {
    pub fn zone_id(mut self, value: impl Into<String>) -> Self {
        self.zone_id = Some(value.into());
        self
    }

    pub fn dns_record_id(mut self, value: impl Into<String>) -> Self {
        self.dns_record_id = Some(value.into());
        self
    }

    pub fn body(mut self, body: Map<String, Value>) -> Self {
        self.body = Some(body);
        self
    }

    pub async fn send(self) -> Result<ResponseValue<Value>, Error<()>> {
        let zone_id = self
            .zone_id
            .ok_or_else(|| Error::new("zone_id is required"))?;
        let dns_record_id = self
            .dns_record_id
            .ok_or_else(|| Error::new("dns_record_id is required"))?;
        let body = self.body.unwrap_or_default();
        let path = format!(
            "/zones/{}/dns_records/{}",
            encode_path(&zone_id),
            encode_path(&dns_record_id)
        );
        self.client
            .send_json(self.client.request(Method::DELETE, &path).json(&body))
            .await
    }
}

#[derive(Clone, Debug)]
pub struct WorkerRoutesListRoutesBuilder<'a> {
    client: &'a Client,
    zone_id: Option<String>,
}

impl<'a> WorkerRoutesListRoutesBuilder<'a> {
    pub fn zone_id(mut self, value: impl Into<String>) -> Self {
        self.zone_id = Some(value.into());
        self
    }

    pub async fn send(self) -> Result<ResponseValue<Value>, Error<()>> {
        let zone_id = self
            .zone_id
            .ok_or_else(|| Error::new("zone_id is required"))?;
        let path = format!("/zones/{}/workers/routes", encode_path(&zone_id));
        self.client
            .send_json(self.client.request(Method::GET, &path))
            .await
    }
}

#[derive(Clone, Debug)]
pub struct WorkerRoutesCreateRouteBuilder<'a> {
    client: &'a Client,
    zone_id: Option<String>,
    body: Option<Map<String, Value>>,
}

impl<'a> WorkerRoutesCreateRouteBuilder<'a> {
    pub fn zone_id(mut self, value: impl Into<String>) -> Self {
        self.zone_id = Some(value.into());
        self
    }

    pub fn body(mut self, body: Map<String, Value>) -> Self {
        self.body = Some(body);
        self
    }

    pub async fn send(self) -> Result<ResponseValue<Value>, Error<()>> {
        let zone_id = self
            .zone_id
            .ok_or_else(|| Error::new("zone_id is required"))?;
        let body = self.body.unwrap_or_default();
        let path = format!("/zones/{}/workers/routes", encode_path(&zone_id));
        self.client
            .send_json(self.client.request(Method::POST, &path).json(&body))
            .await
    }
}

#[derive(Clone, Debug)]
pub struct WorkerRoutesDeleteRouteBuilder<'a> {
    client: &'a Client,
    zone_id: Option<String>,
    route_id: Option<String>,
    body: Option<Map<String, Value>>,
}

impl<'a> WorkerRoutesDeleteRouteBuilder<'a> {
    pub fn zone_id(mut self, value: impl Into<String>) -> Self {
        self.zone_id = Some(value.into());
        self
    }

    pub fn route_id(mut self, value: impl Into<String>) -> Self {
        self.route_id = Some(value.into());
        self
    }

    pub fn body(mut self, body: Map<String, Value>) -> Self {
        self.body = Some(body);
        self
    }

    pub async fn send(self) -> Result<ResponseValue<Value>, Error<()>> {
        let zone_id = self
            .zone_id
            .ok_or_else(|| Error::new("zone_id is required"))?;
        let route_id = self
            .route_id
            .ok_or_else(|| Error::new("route_id is required"))?;
        let body = self.body.unwrap_or_default();
        let path = format!(
            "/zones/{}/workers/routes/{}",
            encode_path(&zone_id),
            encode_path(&route_id)
        );
        self.client
            .send_json(self.client.request(Method::DELETE, &path).json(&body))
            .await
    }
}