x402() Client
Complete API reference for the x402test HTTP client.
Import
Section titled “Import”import { x402, request, X402Request } from "x402test";Constructor
Section titled “Constructor”x402(url: string)
Section titled “x402(url: string)”Creates a new x402 request instance.
const req = x402("http://localhost:4402/api/data");Parameters:
url(string): The URL to make the request to
Returns: X402Request instance
Aliases: request(url)
HTTP Methods
Section titled “HTTP Methods”Sets the HTTP method to GET.
x402(url).get().execute();Returns: this (chainable)
post(body?: unknown)
Section titled “post(body?: unknown)”Sets the HTTP method to POST with optional body.
x402(url).post({ key: "value" }).execute();Parameters:
body(unknown, optional): Request body
Returns: this (chainable)
put(body?: unknown)
Section titled “put(body?: unknown)”Sets the HTTP method to PUT with optional body.
x402(url).put({ key: "updated" }).execute();Parameters:
body(unknown, optional): Request body
Returns: this (chainable)
delete()
Section titled “delete()”Sets the HTTP method to DELETE.
x402(url).delete().execute();Returns: this (chainable)
Headers
Section titled “Headers”header(name: string, value: string)
Section titled “header(name: string, value: string)”Sets a single request header.
x402(url).header("Content-Type", "application/json").execute();Parameters:
name(string): Header namevalue(string): Header value
Returns: this (chainable)
headers(headers: Record<string, string>)
Section titled “headers(headers: Record<string, string>)”Sets multiple request headers.
x402(url) .headers({ "Content-Type": "application/json", Authorization: "Bearer token", }) .execute();Parameters:
headers(Record<string, string>): Object of header key-value pairs
Returns: this (chainable)
body(body: unknown)
Section titled “body(body: unknown)”Sets the request body.
x402(url).body({ key: "value" }).execute();Parameters:
body(unknown): Request body (will be JSON stringified)
Returns: this (chainable)
Payment
Section titled “Payment”withPayment(config: string | { amount: string })
Section titled “withPayment(config: string | { amount: string })”Specifies the maximum amount willing to pay.
// String amountx402(url).withPayment("0.01").execute();
// Object with amountx402(url).withPayment({ amount: "0.01" }).execute();Parameters:
config(string | object): Payment amount in USDC
Returns: this (chainable)
Notes:
- Amount should be in USDC (e.g., “0.01” for 1 cent)
- Client will automatically convert to atomic units
- Must be >= server’s required amount
Expectations
Section titled “Expectations”expectStatus(status: number)
Section titled “expectStatus(status: number)”Asserts the response status code.
await x402(url).withPayment("0.01").expectStatus(200).execute();Parameters:
status(number): Expected HTTP status code
Returns: this (chainable)
Throws: AssertionError if status doesn’t match
expectPaymentSettled()
Section titled “expectPaymentSettled()”Verifies the payment transaction is confirmed on-chain.
await x402(url).withPayment("0.01").expectPaymentSettled().execute();Returns: this (chainable)
Throws: PaymentVerificationError if payment verification fails
expectPaymentAmount(amount: string)
Section titled “expectPaymentAmount(amount: string)”Verifies the exact payment amount in atomic units.
await x402(url) .withPayment("0.01") .expectPaymentAmount("10000") // 0.01 USDC in atomic units .execute();Parameters:
amount(string): Expected amount in atomic units
Returns: this (chainable)
Throws: AssertionError if amount doesn’t match
expectBody(matcher: unknown | ((body: any) => boolean))
Section titled “expectBody(matcher: unknown | ((body: any) => boolean))”Validates the response body.
// Exact matchawait x402(url).expectBody({ key: "value" }).execute();
// Custom validation functionawait x402(url) .expectBody((body) => body.data && body.data.length > 0) .execute();Parameters:
matcher(unknown | function): Expected body or validation function
Returns: this (chainable)
Throws: AssertionError if validation fails
expectHeader(name: string, value: string | RegExp)
Section titled “expectHeader(name: string, value: string | RegExp)”Validates a response header.
// Exact matchawait x402(url).expectHeader("Content-Type", "application/json").execute();
// Regex matchawait x402(url) .expectHeader("Content-Type", /application\/json/) .execute();Parameters:
name(string): Header namevalue(string | RegExp): Expected value or pattern
Returns: this (chainable)
Throws: AssertionError if header doesn’t match
Execution
Section titled “Execution”execute()
Section titled “execute()”Executes the request and returns the response.
const response = await x402(url) .withPayment("0.01") .expectStatus(200) .execute();Returns: Promise<X402Response<T>>
Throws:
X402Error- General request errorsX402ParseError- Failed to parse 402 responsePaymentCreationError- Failed to create paymentPaymentVerificationError- Payment verification failedAssertionError- Expectation not met
Response Type
Section titled “Response Type”X402Response
Section titled “X402Response”The response object returned by execute().
interface X402Response<T> { status: number; statusText: string; headers: Headers; body: T; payment?: { signature: string; amount: string; from: string; to: string; };}Properties:
status(number): HTTP status codestatusText(string): HTTP status textheaders(Headers): Response headersbody(T): Parsed response bodypayment(object, optional): Payment details if payment was made
Complete Example
Section titled “Complete Example”import { x402 } from "x402test";
try { const response = await x402("http://localhost:4402/api/premium") .post({ userId: "123" }) .header("X-Custom", "value") .withPayment("0.10") .expectStatus(200) .expectPaymentSettled() .expectHeader("Content-Type", "application/json") .expectBody((body) => body.success === true) .execute();
console.log("Status:", response.status); console.log("Body:", response.body); console.log("Payment:", response.payment);} catch (error) { console.error("Error:", error.message);}Chaining
Section titled “Chaining”All methods except execute() return the request instance, allowing method chaining:
await x402(url) .post({ data: "value" }) .header("Content-Type", "application/json") .headers({ "X-Custom": "header" }) .body({ additional: "data" }) .withPayment("0.01") .expectStatus(200) .expectPaymentSettled() .expectBody({ success: true }) .execute();Error Handling
Section titled “Error Handling”Using try-catch
Section titled “Using try-catch”import { X402Error, AssertionError } from "x402test";
try { await x402(url).withPayment("0.01").execute();} catch (error) { if (error instanceof X402Error) { console.error("Payment error:", error.message); } else if (error instanceof AssertionError) { console.error("Assertion failed:", error.message); }}Error Types
Section titled “Error Types”All error types are exported:
import { X402Error, X402ParseError, PaymentCreationError, PaymentVerificationError, AssertionError,} from "x402test";TypeScript Support
Section titled “TypeScript Support”Full TypeScript support with generics:
interface ApiResponse { data: string; timestamp: number;}
const response = await x402<ApiResponse>(url).withPayment("0.01").execute();
// response.body is typed as ApiResponseconsole.log(response.body.data);console.log(response.body.timestamp);Next Steps
Section titled “Next Steps”- Payment Methods - Payment creation and handling
- Verification - Payment verification
- Examples - Complete examples