Monetize a REST API with per-request micropayments.
import express from "express" import { createMiddleware } from "@faremeter/middleware/express" import { x402Exact } from "@faremeter/info/solana" const app = express() const microPayment = await createMiddleware({ facilitatorURL: "https://facilitator.corbits.dev", accepts: [ ...x402Exact({ network: "devnet", payTo: process.env.MERCHANT_ADDRESS, asset: "USDC", amount: "100", }), ], }) app.get("/api/weather/:city", microPayment, (req, res) => { res.json({ city: req.params.city, temperature: 72, conditions: "sunny", }) }) app.get("/api/quote", microPayment, (req, res) => { res.json({ quote: "The best way to predict the future is to invent it.", author: "Alan Kay", }) }) app.listen(3000)
import "dotenv/config" import { payer } from "@faremeter/rides" import { getLogger } from "@faremeter/logs" const logger = await getLogger(["client"]) await payer.addLocalWallet(process.env.PAYER_KEYPAIR_PATH) const weather = await payer.fetch("http://localhost:3000/api/weather/seattle") logger.info(JSON.stringify(await weather.json())) const quote = await payer.fetch("http://localhost:3000/api/quote") logger.info(JSON.stringify(await quote.json()))
# Terminal 1 MERCHANT_ADDRESS=7xKXwxRPMo2sUAT5... pnpm tsx server.ts # Terminal 2 PAYER_KEYPAIR_PATH=~/.config/solana/id.json pnpm tsx client.ts
Was this page helpful?