clawspec-core 0.4.4

Core library for generating OpenAPI specifications from tests
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
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
use std::ops::{Range, RangeInclusive};

use serde::Serialize;
use utoipa::ToSchema;

use super::ApiCall;
use crate::client::parameters::{ParamValue, ParameterValue};
use crate::client::response::ExpectedStatusCodes;
#[cfg(feature = "redaction")]
use crate::client::response::RequestBodyRedactionBuilder;
use crate::client::security::SecurityRequirement;
use crate::client::{ApiClientError, CallBody, CallCookies, CallHeaders, CallQuery};

impl ApiCall {
    // =============================================================================
    // OpenAPI Metadata Methods
    // =============================================================================
    pub fn with_operation_id(mut self, operation_id: impl Into<String>) -> Self {
        self.metadata.operation_id = operation_id.into();
        self
    }

    /// Sets the operation description for OpenAPI documentation.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use clawspec_core::ApiClient;
    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let mut client = ApiClient::builder().build()?;
    /// let call = client.get("/users")?.with_description("Retrieve all users");
    /// # Ok(())
    /// # }
    /// ```
    pub fn with_description(mut self, description: impl Into<String>) -> Self {
        self.metadata.description = Some(description.into());
        self
    }

    /// Sets the operation tags for OpenAPI categorization.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use clawspec_core::ApiClient;
    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let mut client = ApiClient::builder().build()?;
    /// let call = client.get("/users")?.with_tags(vec!["users", "admin"]);
    /// // Also works with arrays, slices, or any IntoIterator
    /// let call = client.get("/users")?.with_tags(["users", "admin"]);
    /// # Ok(())
    /// # }
    /// ```
    pub fn with_tags<I, T>(mut self, tags: I) -> Self
    where
        I: IntoIterator<Item = T>,
        T: Into<String>,
    {
        self.metadata.tags = Some(tags.into_iter().map(|t| t.into()).collect());
        self
    }

    /// Adds a single tag to the operation for OpenAPI categorization.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use clawspec_core::ApiClient;
    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let mut client = ApiClient::builder().build()?;
    /// let call = client.get("/users")?.with_tag("users").with_tag("admin");
    /// # Ok(())
    /// # }
    /// ```
    pub fn with_tag(mut self, tag: impl Into<String>) -> Self {
        self.metadata
            .tags
            .get_or_insert_with(Vec::new)
            .push(tag.into());
        self
    }

    /// Sets a response description for the actual returned status code.
    ///
    /// This method allows you to document what the response means for your API endpoint.
    /// The description will be applied to whatever status code is actually returned by the server
    /// and included in the generated OpenAPI specification.
    ///
    /// **Note**: This method is only available with the `redaction` feature enabled.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use clawspec_core::ApiClient;
    /// # #[cfg(feature = "redaction")]
    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let mut client = ApiClient::builder().build()?;
    /// let call = client.get("/users/{id}")?
    ///     .with_response_description("User details if found, or error information");
    /// # Ok(())
    /// # }
    /// ```
    #[cfg(feature = "redaction")]
    pub fn with_response_description(mut self, description: impl Into<String>) -> Self {
        self.response_description = Some(description.into());
        self
    }

    /// Excludes this API call from OpenAPI collection and documentation generation.
    ///
    /// When called, this API call will be executed normally but will not appear
    /// in the generated OpenAPI specification. This is useful for:
    /// - Health check endpoints
    /// - Debug/diagnostic endpoints
    /// - Authentication/session management calls
    /// - Test setup/teardown calls
    /// - Internal utility endpoints
    /// - Administrative endpoints not part of public API
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use clawspec_core::ApiClient;
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let mut client = ApiClient::builder().build()?;
    ///
    /// // Health check that won't appear in OpenAPI spec
    /// client
    ///     .get("/health")?
    ///     .without_collection()
    ///     .await?
    ///     .as_empty()
    ///     .await?;
    ///
    /// // Debug endpoint excluded from documentation
    /// client
    ///     .get("/debug/status")?
    ///     .without_collection()
    ///     .await?
    ///     .as_text()
    ///     .await?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn without_collection(mut self) -> Self {
        self.skip_collection = true;
        self
    }

    /// Sets the security requirements for this specific operation.
    ///
    /// This method overrides the default security configured on the client.
    /// Use this when an endpoint requires different authentication than the default.
    ///
    /// # Parameters
    ///
    /// * `requirement` - The security requirement to apply to this operation
    ///
    /// # Examples
    ///
    /// ```rust
    /// use clawspec_core::{ApiClient, SecurityScheme, SecurityRequirement};
    ///
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let mut client = ApiClient::builder()
    ///     .with_security_scheme("bearerAuth", SecurityScheme::bearer())
    ///     .with_security_scheme("adminAuth", SecurityScheme::bearer_with_format("JWT"))
    ///     .with_default_security(SecurityRequirement::new("bearerAuth"))
    ///     .build()?;
    ///
    /// // This endpoint requires admin authentication instead of the default
    /// client
    ///     .post("/admin/users")?
    ///     .with_security(SecurityRequirement::new("adminAuth"))
    ///     .await?
    ///     .as_empty()
    ///     .await?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Generated OpenAPI
    ///
    /// ```yaml
    /// paths:
    ///   /admin/users:
    ///     post:
    ///       security:
    ///         - adminAuth: []
    /// ```
    pub fn with_security(mut self, requirement: SecurityRequirement) -> Self {
        self.security = Some(vec![requirement]);
        self
    }

    /// Sets multiple security requirements for this operation (OR relationship).
    ///
    /// When multiple security requirements are set, they represent alternative
    /// authentication methods. The client can satisfy any one of them.
    ///
    /// # Parameters
    ///
    /// * `requirements` - Iterator of security requirements
    ///
    /// # Examples
    ///
    /// ```rust
    /// use clawspec_core::{ApiClient, SecurityScheme, SecurityRequirement, ApiKeyLocation};
    ///
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let mut client = ApiClient::builder()
    ///     .with_security_scheme("bearerAuth", SecurityScheme::bearer())
    ///     .with_security_scheme("apiKey", SecurityScheme::api_key("X-API-Key", ApiKeyLocation::Header))
    ///     .build()?;
    ///
    /// // This endpoint accepts either bearer token OR API key
    /// client
    ///     .get("/data")?
    ///     .with_securities([
    ///         SecurityRequirement::new("bearerAuth"),
    ///         SecurityRequirement::new("apiKey"),
    ///     ])
    ///     .await?
    ///     .as_empty()
    ///     .await?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn with_securities(
        mut self,
        requirements: impl IntoIterator<Item = SecurityRequirement>,
    ) -> Self {
        self.security = Some(requirements.into_iter().collect());
        self
    }

    /// Marks this operation as not requiring authentication.
    ///
    /// Use this for public endpoints that don't need security, overriding
    /// any default security configured on the client.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use clawspec_core::{ApiClient, SecurityScheme, SecurityRequirement};
    ///
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let mut client = ApiClient::builder()
    ///     .with_security_scheme("bearerAuth", SecurityScheme::bearer())
    ///     .with_default_security(SecurityRequirement::new("bearerAuth"))
    ///     .build()?;
    ///
    /// // Public endpoint - no authentication needed
    /// client
    ///     .get("/public/health")?
    ///     .without_security()
    ///     .await?
    ///     .as_empty()
    ///     .await?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Generated OpenAPI
    ///
    /// ```yaml
    /// paths:
    ///   /public/health:
    ///     get:
    ///       security: []  # Empty array means no security required
    /// ```
    pub fn without_security(mut self) -> Self {
        self.security = Some(vec![]); // Empty array = no security required
        self
    }

    // =============================================================================
    // Request Configuration Methods
    // =============================================================================

    pub fn with_query(mut self, query: CallQuery) -> Self {
        self.query = query;
        self
    }

    pub fn with_headers_option(mut self, headers: Option<CallHeaders>) -> Self {
        self.headers = match (self.headers.take(), headers) {
            (Some(existing), Some(new)) => Some(existing.merge(new)),
            (existing, new) => existing.or(new),
        };
        self
    }

    /// Adds headers to the API call, merging with any existing headers.
    ///
    /// This is a convenience method that automatically wraps the headers in Some().
    pub fn with_headers(self, headers: CallHeaders) -> Self {
        self.with_headers_option(Some(headers))
    }

    /// Convenience method to add a single header.
    ///
    /// This method automatically handles type conversion and merges with existing headers.
    /// If a header with the same name already exists, the new value will override it.
    ///
    /// # Examples
    ///
    /// ## Basic Usage
    /// ```rust
    /// # use clawspec_core::ApiClient;
    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let mut client = ApiClient::builder().build()?;
    /// let call = client.get("/users")?
    ///     .with_header("Authorization", "Bearer token123")
    ///     .with_header("X-Request-ID", "abc-123-def");
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// ## Type Flexibility and Edge Cases
    /// ```rust
    /// # use clawspec_core::ApiClient;
    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let mut client = ApiClient::builder().build()?;
    ///
    /// // Different value types are automatically converted
    /// let call = client.post("/api/data")?
    ///     .with_header("Content-Length", 1024_u64)           // Numeric values
    ///     .with_header("X-Retry-Count", 3_u32)               // Different numeric types
    ///     .with_header("X-Debug", true)                      // Boolean values
    ///     .with_header("X-Session-ID", "session-123");       // String values
    ///
    /// // Headers can be chained and overridden
    /// let call = client.get("/protected")?
    ///     .with_header("Authorization", "Bearer old-token")
    ///     .with_header("Authorization", "Bearer new-token");  // Overrides previous value
    /// # Ok(())
    /// # }
    /// ```
    pub fn with_header<T: ParameterValue>(
        self,
        name: impl Into<String>,
        value: impl Into<ParamValue<T>>,
    ) -> Self {
        let headers = CallHeaders::new().add_header(name, value);
        self.with_headers(headers)
    }

    /// Adds cookies to the API call, merging with any existing cookies.
    ///
    /// This method accepts a `CallCookies` instance and merges it with any existing
    /// cookies on the request. Cookies are sent in the HTTP Cookie header and can
    /// be used for session management, authentication, and storing user preferences.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use clawspec_core::{ApiClient, CallCookies};
    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let mut client = ApiClient::builder().build()?;
    /// let cookies = CallCookies::new()
    ///     .add_cookie("session_id", "abc123")
    ///     .add_cookie("user_id", 456);
    ///
    /// let call = client.get("/dashboard")?
    ///     .with_cookies(cookies);
    /// # Ok(())
    /// # }
    /// ```
    pub fn with_cookies(mut self, cookies: CallCookies) -> Self {
        self.cookies = match self.cookies.take() {
            Some(existing) => Some(existing.merge(cookies)),
            None => Some(cookies),
        };
        self
    }

    /// Convenience method to add a single cookie.
    ///
    /// This method automatically handles type conversion and merges with existing cookies.
    /// If a cookie with the same name already exists, the new value will override it.
    ///
    /// # Examples
    ///
    /// ## Basic Usage
    /// ```rust
    /// # use clawspec_core::ApiClient;
    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let mut client = ApiClient::builder().build()?;
    /// let call = client.get("/dashboard")?
    ///     .with_cookie("session_id", "abc123")
    ///     .with_cookie("user_id", 456);
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// ## Type Flexibility and Edge Cases
    /// ```rust
    /// # use clawspec_core::ApiClient;
    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let mut client = ApiClient::builder().build()?;
    ///
    /// // Different value types are automatically converted
    /// let call = client.get("/preferences")?
    ///     .with_cookie("theme", "dark")                    // String values
    ///     .with_cookie("user_id", 12345_u64)              // Numeric values
    ///     .with_cookie("is_premium", true)                // Boolean values
    ///     .with_cookie("selected_tags", vec!["rust", "web"]); // Array values
    ///
    /// // Cookies can be chained and overridden
    /// let call = client.get("/profile")?
    ///     .with_cookie("session_id", "old-session")
    ///     .with_cookie("session_id", "new-session");      // Overrides previous value
    /// # Ok(())
    /// # }
    /// ```
    pub fn with_cookie<T: ParameterValue>(
        self,
        name: impl Into<String>,
        value: impl Into<ParamValue<T>>,
    ) -> Self {
        let cookies = CallCookies::new().add_cookie(name, value);
        self.with_cookies(cookies)
    }

    /// Overrides the authentication for this specific request.
    ///
    /// This method allows you to use different authentication for a specific request,
    /// overriding the default authentication configured on the API client.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use clawspec_core::{ApiClient, Authentication};
    ///
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// // Client with default authentication
    /// let mut client = ApiClient::builder()
    ///     .with_authentication(Authentication::Bearer("default-token".into()))
    ///     .build()?;
    ///
    /// // Use different authentication for a specific request
    /// let response = client
    ///     .get("/admin/users")?
    ///     .with_authentication(Authentication::Bearer("admin-token".into()))
    ///     .await?;
    ///
    /// // Remove authentication for a public endpoint
    /// let response = client
    ///     .get("/public/health")?
    ///     .with_authentication_none()
    ///     .await?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn with_authentication(mut self, authentication: crate::client::Authentication) -> Self {
        self.authentication = Some(authentication);
        self
    }

    /// Removes authentication for this specific request.
    ///
    /// This is useful when making requests to public endpoints that don't require
    /// authentication, even when the client has default authentication configured.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use clawspec_core::{ApiClient, Authentication};
    ///
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// // Client with default authentication
    /// let mut client = ApiClient::builder()
    ///     .with_authentication(Authentication::Bearer("token".into()))
    ///     .build()?;
    ///
    /// // Remove authentication for public endpoint
    /// let response = client
    ///     .get("/public/status")?
    ///     .with_authentication_none()
    ///     .await?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn with_authentication_none(mut self) -> Self {
        self.authentication = None;
        self
    }

    // =============================================================================
    // Status Code Validation Methods
    // =============================================================================

    /// Sets the expected status codes for this request using an inclusive range.
    ///
    /// By default, status codes 200..500 are considered successful.
    /// Use this method to customize which status codes should be accepted.
    ///
    /// # Examples
    ///
    /// ## Basic Usage
    /// ```rust
    /// # use clawspec_core::ApiClient;
    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let mut client = ApiClient::builder().build()?;
    ///
    /// // Accept only 200 to 201 (inclusive)
    /// let call = client.post("/users")?.with_status_range_inclusive(200..=201);
    ///
    /// // Accept any 2xx status code
    /// let call = client.get("/users")?.with_status_range_inclusive(200..=299);
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// ## Edge Cases
    /// ```rust
    /// # use clawspec_core::ApiClient;
    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let mut client = ApiClient::builder().build()?;
    ///
    /// // Single status code range (equivalent to with_expected_status)
    /// let call = client.get("/health")?.with_status_range_inclusive(200..=200);
    ///
    /// // Accept both success and client error ranges  
    /// let call = client.delete("/users/123")?
    ///     .with_status_range_inclusive(200..=299)
    ///     .add_expected_status_range_inclusive(400..=404);
    ///
    /// // Handle APIs that return 2xx or 3xx for different success states
    /// let call = client.post("/async-operation")?.with_status_range_inclusive(200..=302);
    /// # Ok(())
    /// # }
    /// ```
    pub fn with_status_range_inclusive(mut self, range: RangeInclusive<u16>) -> Self {
        self.expected_status_codes = ExpectedStatusCodes::from_inclusive_range(range);
        self
    }

    /// Sets the expected status codes for this request using an exclusive range.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use clawspec_core::ApiClient;
    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let mut client = ApiClient::builder().build()?;
    ///
    /// // Accept 200 to 299 (200 included, 300 excluded)
    /// let call = client.get("/users")?.with_status_range(200..300);
    /// # Ok(())
    /// # }
    /// ```
    pub fn with_status_range(mut self, range: Range<u16>) -> Self {
        self.expected_status_codes = ExpectedStatusCodes::from_exclusive_range(range);
        self
    }

    /// Sets a single expected status code for this request.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use clawspec_core::ApiClient;
    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let mut client = ApiClient::builder().build()?;
    ///
    /// // Accept only 204 for DELETE operations
    /// let call = client.delete("/users/123")?.with_expected_status(204);
    /// # Ok(())
    /// # }
    /// ```
    pub fn with_expected_status(mut self, status: u16) -> Self {
        self.expected_status_codes = ExpectedStatusCodes::from_single(status);
        self
    }

    /// Adds an additional expected status code to the existing set.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use clawspec_core::ApiClient;
    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let mut client = ApiClient::builder().build()?;
    ///
    /// // Accept 200..299 and also 404
    /// let call = client.get("/users")?.with_status_range_inclusive(200..=299).add_expected_status(404);
    /// # Ok(())
    /// # }
    /// ```
    pub fn add_expected_status(mut self, status: u16) -> Self {
        self.expected_status_codes = self.expected_status_codes.add_expected_status(status);
        self
    }

    /// Adds an additional expected status range (inclusive) to the existing set.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use clawspec_core::ApiClient;
    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let mut client = ApiClient::builder().build()?;
    ///
    /// // Accept 200..=204 and also 400..=402
    /// let call = client.post("/users")?.with_status_range_inclusive(200..=204).add_expected_status_range_inclusive(400..=402);
    /// # Ok(())
    /// # }
    /// ```
    pub fn add_expected_status_range_inclusive(mut self, range: RangeInclusive<u16>) -> Self {
        self.expected_status_codes = self.expected_status_codes.add_expected_range(range);
        self
    }

    /// Adds an additional expected status range (exclusive) to the existing set.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use clawspec_core::ApiClient;
    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let mut client = ApiClient::builder().build()?;
    ///
    /// // Accept 200..=204 and also 400..403
    /// let call = client.post("/users")?.with_status_range_inclusive(200..=204).add_expected_status_range(400..403);
    /// # Ok(())
    /// # }
    /// ```
    pub fn add_expected_status_range(mut self, range: Range<u16>) -> Self {
        self.expected_status_codes = self.expected_status_codes.add_exclusive_range(range);
        self
    }

    /// Convenience method to accept only 2xx status codes (200..300).
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use clawspec_core::ApiClient;
    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let mut client = ApiClient::builder().build()?;
    /// let call = client.get("/users")?.with_success_only();
    /// # Ok(())
    /// # }
    /// ```
    pub fn with_success_only(self) -> Self {
        self.with_status_range(200..300)
    }

    /// Convenience method to accept 2xx and 4xx status codes (200..500, excluding 3xx).
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use clawspec_core::ApiClient;
    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let mut client = ApiClient::builder().build()?;
    /// let call = client.post("/users")?.with_client_errors();
    /// # Ok(())
    /// # }
    /// ```
    pub fn with_client_errors(self) -> Self {
        self.with_status_range_inclusive(200..=299)
            .add_expected_status_range_inclusive(400..=499)
    }

    /// Sets the expected status codes using an `ExpectedStatusCodes` instance.
    ///
    /// This method allows you to pass pre-configured `ExpectedStatusCodes` instances,
    /// which is particularly useful with the `expected_status_codes!` macro.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use clawspec_core::{ApiClient, expected_status_codes};
    ///
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let mut client = ApiClient::builder().build()?;
    ///
    /// // Using the macro with with_expected_status_codes
    /// let call = client.get("/users")?
    ///     .with_expected_status_codes(expected_status_codes!(200-299));
    ///
    /// // Using manually created ExpectedStatusCodes
    /// let codes = clawspec_core::ExpectedStatusCodes::from_inclusive_range(200..=204)
    ///     .add_expected_status(404);
    /// let call = client.get("/items")?.with_expected_status_codes(codes);
    /// # Ok(())
    /// # }
    /// ```
    pub fn with_expected_status_codes(mut self, codes: ExpectedStatusCodes) -> Self {
        self.expected_status_codes = codes;
        self
    }

    /// Sets expected status codes from a single `http::StatusCode`.
    ///
    /// This method provides **compile-time validation** of status codes through the type system.
    /// Unlike the `u16` variants, this method does not perform runtime validation since
    /// `http::StatusCode` guarantees valid HTTP status codes at compile time.
    ///
    /// # Example
    ///
    /// ```rust
    /// use clawspec_core::ApiClient;
    /// use http::StatusCode;
    ///
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let mut client = ApiClient::builder().build()?;
    ///
    /// let call = client.get("/users")?
    ///     .with_expected_status_code(StatusCode::OK);
    /// # Ok(())
    /// # }
    /// ```
    pub fn with_expected_status_code(self, status: http::StatusCode) -> Self {
        self.with_expected_status_codes(ExpectedStatusCodes::from_status_code(status))
    }

    /// Sets expected status codes from a range of `http::StatusCode`.
    ///
    /// This method provides **compile-time validation** of status codes through the type system.
    /// Unlike the `u16` variants, this method does not perform runtime validation since
    /// `http::StatusCode` guarantees valid HTTP status codes at compile time.
    ///
    /// # Example
    ///
    /// ```rust
    /// use clawspec_core::ApiClient;
    /// use http::StatusCode;
    ///
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let mut client = ApiClient::builder().build()?;
    ///
    /// let call = client.get("/users")?
    ///     .with_expected_status_code_range(StatusCode::OK..=StatusCode::NO_CONTENT);
    /// # Ok(())
    /// # }
    /// ```
    pub fn with_expected_status_code_range(self, range: RangeInclusive<http::StatusCode>) -> Self {
        self.with_expected_status_codes(ExpectedStatusCodes::from_status_code_range_inclusive(
            range,
        ))
    }

    // =============================================================================
    // Request Body Methods
    // =============================================================================

    /// Sets the request body to JSON.
    ///
    /// This method serializes the provided data as JSON and sets the
    /// Content-Type header to `application/json`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use clawspec_core::ApiClient;
    /// # use serde::Serialize;
    /// # use utoipa::ToSchema;
    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// #[derive(Serialize, ToSchema)]
    /// struct CreateUser {
    ///     name: String,
    ///     email: String,
    /// }
    ///
    /// let mut client = ApiClient::builder().build()?;
    /// let user_data = CreateUser {
    ///     name: "John Doe".to_string(),
    ///     email: "john@example.com".to_string(),
    /// };
    ///
    /// let call = client.post("/users")?.json(&user_data)?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn json<T>(mut self, t: &T) -> Result<Self, ApiClientError>
    where
        T: Serialize + ToSchema + 'static,
    {
        let body = CallBody::json(t)?;
        self.body = Some(body);
        Ok(self)
    }

    /// Sets the request body to JSON with redaction support for OpenAPI examples.
    ///
    /// This method returns a [`RequestBodyRedactionBuilder`] that allows you to
    /// redact sensitive values (like passwords, API keys, tokens) in the OpenAPI
    /// documentation while sending the original values in the HTTP request.
    ///
    /// **Key principle:**
    /// - **HTTP Request**: Uses the original value with real data for testing
    /// - **OpenAPI Example**: Uses the redacted value with stable placeholders
    ///
    /// This is useful when you want to:
    /// - Hide sensitive credentials in documentation
    /// - Create stable, deterministic OpenAPI examples
    /// - Test with real data while documenting with sanitized examples
    ///
    /// # Type Parameters
    ///
    /// * `T` - The type to serialize. Must implement `Serialize`, `ToSchema`, and `Clone`.
    ///
    /// # Examples
    ///
    /// ## Basic Usage
    ///
    /// ```rust
    /// # use clawspec_core::ApiClient;
    /// # use serde::Serialize;
    /// # use utoipa::ToSchema;
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// #[derive(Clone, Serialize, ToSchema)]
    /// struct LoginRequest {
    ///     username: String,
    ///     password: String,
    /// }
    ///
    /// let mut client = ApiClient::builder().build()?;
    /// let request = LoginRequest {
    ///     username: "alice".to_string(),
    ///     password: "secret123".to_string(),
    /// };
    ///
    /// // The HTTP request will contain the real password,
    /// // but the OpenAPI example will show "[REDACTED]"
    /// client
    ///     .post("/auth/login")?
    ///     .json_redacted(&request)?
    ///     .redact("/password", "[REDACTED]")?
    ///     .await?;  // IntoFuture - no .finish() needed
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// ## Multiple Redactions
    ///
    /// ```rust
    /// # use clawspec_core::ApiClient;
    /// # use serde::Serialize;
    /// # use utoipa::ToSchema;
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// #[derive(Clone, Serialize, ToSchema)]
    /// struct CreateApiKey {
    ///     name: String,
    ///     secret: String,
    ///     internal_id: String,
    /// }
    ///
    /// let mut client = ApiClient::builder().build()?;
    /// let request = CreateApiKey {
    ///     name: "my-key".to_string(),
    ///     secret: "sk-live-abc123def456".to_string(),
    ///     internal_id: "internal-ref-789".to_string(),
    /// };
    ///
    /// client
    ///     .post("/api-keys")?
    ///     .json_redacted(&request)?
    ///     .redact("/secret", "[REDACTED_SECRET]")?
    ///     .redact_remove("/internal_id")?  // Remove entirely from docs
    ///     .await?;  // IntoFuture - no .finish() needed
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// ## JSONPath Wildcards
    ///
    /// ```rust
    /// # use clawspec_core::ApiClient;
    /// # use serde::Serialize;
    /// # use utoipa::ToSchema;
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// #[derive(Clone, Serialize, ToSchema)]
    /// struct BulkCreateUsers {
    ///     users: Vec<UserData>,
    /// }
    ///
    /// #[derive(Clone, Serialize, ToSchema)]
    /// struct UserData {
    ///     name: String,
    ///     password: String,
    /// }
    ///
    /// let mut client = ApiClient::builder().build()?;
    /// let request = BulkCreateUsers {
    ///     users: vec![
    ///         UserData { name: "alice".to_string(), password: "secret1".to_string() },
    ///         UserData { name: "bob".to_string(), password: "secret2".to_string() },
    ///     ],
    /// };
    ///
    /// // Redact ALL passwords in the array
    /// client
    ///     .post("/users/bulk")?
    ///     .json_redacted(&request)?
    ///     .redact("$.users[*].password", "[REDACTED]")?
    ///     .await?;  // IntoFuture - no .finish() needed
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    /// Returns an error if JSON serialization fails.
    ///
    /// # Feature Flag
    ///
    /// This method requires the `redaction` feature to be enabled:
    ///
    /// ```toml
    /// [dependencies]
    /// clawspec-core = { version = "...", features = ["redaction"] }
    /// ```
    #[cfg(feature = "redaction")]
    #[cfg_attr(docsrs, doc(cfg(feature = "redaction")))]
    pub fn json_redacted<T>(self, t: &T) -> Result<RequestBodyRedactionBuilder<T>, ApiClientError>
    where
        T: Serialize + ToSchema + Clone + 'static,
    {
        let body = CallBody::json_without_example(t)?;
        let json_value = serde_json::to_value(t)?;
        Ok(RequestBodyRedactionBuilder::new(
            t.clone(),
            json_value,
            body,
            self,
        ))
    }

    /// Sets the request body to form-encoded data.
    ///
    /// This method serializes the provided data as `application/x-www-form-urlencoded`
    /// and sets the appropriate Content-Type header.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use clawspec_core::ApiClient;
    /// # use serde::Serialize;
    /// # use utoipa::ToSchema;
    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// #[derive(Serialize, ToSchema)]
    /// struct LoginForm {
    ///     username: String,
    ///     password: String,
    /// }
    ///
    /// let mut client = ApiClient::builder().build()?;
    /// let form_data = LoginForm {
    ///     username: "user@example.com".to_string(),
    ///     password: "secret".to_string(),
    /// };
    ///
    /// let call = client.post("/login")?.form(&form_data)?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn form<T>(mut self, t: &T) -> Result<Self, ApiClientError>
    where
        T: Serialize + ToSchema + 'static,
    {
        let body = CallBody::form(t)?;
        self.body = Some(body);
        Ok(self)
    }

    /// Sets the request body to raw binary data with a custom content type.
    ///
    /// This method allows you to send arbitrary binary data with a specified
    /// content type. This is useful for sending data that doesn't fit into
    /// the standard JSON or form categories.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use clawspec_core::ApiClient;
    /// # use headers::ContentType;
    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let mut client = ApiClient::builder().build()?;
    /// // Send XML data
    /// let xml_data = r#"<?xml version="1.0"?><user><name>John</name></user>"#;
    /// let call = client.post("/import")?
    ///     .raw(xml_data.as_bytes().to_vec(), ContentType::xml());
    ///
    /// // Send binary file
    /// let binary_data = vec![0xFF, 0xFE, 0xFD];
    /// let call = client.post("/upload")?
    ///     .raw(binary_data, ContentType::octet_stream());
    /// # Ok(())
    /// # }
    /// ```
    pub fn raw(mut self, data: Vec<u8>, content_type: headers::ContentType) -> Self {
        let body = CallBody::raw(data, content_type);
        self.body = Some(body);
        self
    }

    /// Sets the request body to plain text.
    ///
    /// This is a convenience method for sending plain text data with
    /// `text/plain` content type.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use clawspec_core::ApiClient;
    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let mut client = ApiClient::builder().build()?;
    /// let call = client.post("/notes")?.text("This is a plain text note");
    /// # Ok(())
    /// # }
    /// ```
    pub fn text(mut self, text: &str) -> Self {
        let body = CallBody::text(text);
        self.body = Some(body);
        self
    }

    /// Sets the request body to multipart/form-data.
    ///
    /// This method creates a multipart body with a generated boundary and supports
    /// both text fields and file uploads. This is commonly used for file uploads
    /// or when combining different types of data in a single request.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use clawspec_core::ApiClient;
    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let mut client = ApiClient::builder().build()?;
    /// let parts = vec![
    ///     ("title", "My Document"),
    ///     ("file", "file content here"),
    /// ];
    /// let call = client.post("/upload")?.multipart(parts);
    /// # Ok(())
    /// # }
    /// ```
    pub fn multipart(mut self, parts: Vec<(&str, &str)>) -> Self {
        let body = CallBody::multipart(parts);
        self.body = Some(body);
        self
    }
}

// Call