- B2B checkout: VAT check, payment link, mail and ERP order
- Transactional price import, then reports in every format
- Sync an e-shop catalogue into MongoDB
- Read supplier invoices from an Office 365 mailbox
- Health check of the outgoing mail queue
- Triage the mails in error and replay them
- Declare the legacy ERP databases: AS/400, DB2, Oracle, Firebird
- Collect the orders sent by mail to a POP3 mailbox
- IMAP: supplier confirmations only, as JSON, moved to a folder
- Notify an internal HTTP webhook with a JSON event
- Validate a payload, then patch it
- Secure an internal API: sign a JWT, verify it, and see why a token is refused
- Check orders against the OpenAPI document of a partner before sending them
B2B checkout: VAT check, payment link, mail and ERP order
A business customer orders online. The script checks its EU VAT number with the VIES SOAP service, creates a Stripe Checkout session, e-mails the payment link, and posts the order to the ERP REST API.
#1. Check the VAT number with the VIES SOAP service; -> "[vat]" "40303265045"; -> "[answer]" (soap https "https://ec.europa.eu/taxation_customs/vies/services/checkVatService" "{}" "" "text/xml; charset=utf-8" (concat "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:urn=\"urn:ec.europa.eu:taxud:vies:services:checkVat:types\"><soapenv:Header/><soapenv:Body><urn:checkVat><urn:countryCode>FR</urn:countryCode><urn:vatNumber>" [vat] "</urn:vatNumber></urn:checkVat></soapenv:Body></soapenv:Envelope>")); xml load "rx_vies" [answer]; -> "[valid]" (xml select text "rx_vies" "//*[local-name()='valid']"); -> "[company]" (xml select text "rx_vies" "//*[local-name()='name']"); #2. Stripe Checkout session, amounts in cents; json load "rx_pay" (stripe session "[{\"Product\": \"Order WEB-7731\", \"UnitAmount\": \"129000\", \"Currency\": \"eur\", \"Quantity\": \"1\"}]" "https://shop.example.com/paid?o=WEB-7731" "https://shop.example.com/cart" (parameter get value "STRIPE_SECRET_KEY")); #3. SMTP connection, then the mail with the payment link; cm set "rx_cm_smtp" {execute "mail.smtp.config.get" "[hostname]" "smtp.example.com" "[port]" "465" "[sender]" "shop@example.com" "[user]" "shop@example.com" "[password]" "change_me" "[authentication]" true "[tls]" true "[connectTimeout]" "10000" "[sessionTimeout]" "60000" ;}; mail send "rx_cm_smtp" "buyer@customer.example.com" "" "sales@example.com" "Your order WEB-7731" (concat "Hello " [company] ",<br>please pay your order here: " (json select "rx_pay" "/url")) "[]"; #4. Order to the ERP; json load "rx_hdr" (concat "{\"Authorization\": \"Bearer " (parameter get value "ERP_TOKEN") "\"}"); json load "rx_erp" (rest https_json_post "https://erp.example.com/api/v1/orders" (json doc "rx_hdr") "[]" (concat "{\"ref\": \"WEB-7731\", \"vat\": \"FR" [vat] "\", \"vat_valid\": " [valid] ", \"stripe_session\": \"" (json select "rx_pay" "/id") "\", \"amount\": 1290.00}")); concat "VAT valid: " [valid] ", Stripe session " (json select "rx_pay" "/id") ", ERP answer: " (json select "rx_erp" "/reponse");
- Test with the Stripe test key
sk_test_...and the published test cards before going live - An old SOAP service on plain HTTP:
soap httptakes the same parameters, plus an optional proxy
Transactional price import, then reports in every format
The pricing team sends a CSV of new prices. The script updates the ERP database in one transaction (all or nothing), checks the result, then produces the reports the teams ask for: xlsx, csv, PDF, XML, HTML and a JSON block for an API.
#1. Connection to the ERP database, manual transactions; cm set "rx_cm_erp" {execute "db.postgresql.config.get" "[hostname]" "10.0.0.5" "[port]" "5432" "[database]" "erp" "[user]" "mentdb" "[password]" "change_me" ;}; sql set_timeout 60; sql connect "rx_erp" {cm get "rx_cm_erp";}; sql auto_commit "rx_erp" false; #2. All the prices or none; try { csv parse (mql "P") (mql "tmp/rx_prices.csv") (mql ";") (mql "\"") (mql "") { sql dml "rx_erp" (concat "update product set price=" (sql encode [P_price]) ", label=" (sql encode_std [P_label]) " where sku=" (sql encode [P_sku])); }; sql commit "rx_erp"; } { sql rollback "rx_erp"; } "[err]"; #3. Checks; -> "[missing]" (sql value "rx_erp" "select count(*) from product where price is null"); json load "rx_top" (sql row "rx_erp" "select sku, price from product order by price desc limit 1"); json load "rx_cats" (sql col_distinct "rx_erp" "select category from product"); -> "[low]" ""; sql parse "rx_erp" "R" "select sku from product where stock < 5" { -> "[low]" (concat [low] [R_sku] " "); }; #4. Reports; -> "[q]" "select sku, label, category, price from product order by sku"; sql to excelx "rx_erp" "products" [q] "tmp/rx_products.xlsx"; sql to excel "rx_erp" "products" [q] "tmp/rx_products.xls"; sql to csv_file "rx_erp" "tmp/rx_products.csv" [q] ";" "\""; sql to pdf "rx_erp" "products" [q] "tmp/rx_products.pdf"; -> "[xml]" (sql to xml "rx_erp" "products" [q]); -> "[html]" (sql to html "rx_erp" "products" [q]); -> "[csv]" (sql to csv "rx_erp" "products" (concat [q] " limit 10") "," "\""); json load "rx_json" (sql to json "rx_erp" "products" (concat [q] " limit 100")); #5. Large table: read it by blocks of 500 rows; sql block open "rx_erp" "product" "select sku, price from product"; json load "rx_block1" (sql block to_json 500); sql block close; sql disconnect "rx_erp"; concat "{\"missing_prices\": " [missing] ", \"top\": " (json doc "rx_top") ", \"low_stock\": \"" (string trim [low]) "\", \"open_sessions\": " (sql show) "}";
sql encodeandsql encode_stdrun without a database: trysql encode "O'Brien"alone, it returns 'O''Brien'- Put the PDF table directly in your own layout with
pdf table add ... (sql to json ...)
Sync an e-shop catalogue into MongoDB
A marketplace keeps a copy of a partner catalogue in MongoDB. The script reads the products from the partner REST API, upserts them in a collection, flags the sold-out ones, removes the discontinued ones, reads the 5 most expensive back and confirms the sync to the partner.
#1. Products from the partner API; json load "rx_hdr" (concat "{\"Authorization\": \"Bearer " (parameter get value "PARTNER_TOKEN") "\", \"Accept\": \"application/json\"}"); json load "rx_resp" (rest https "get" "https://api.partner.example.com/v2/products" "page=1&per_page=100" (json doc "rx_hdr") "[]"); json load "rx_products" (json select "rx_resp" "/reponse"); #2. MongoDB connection: a configuration JSON, the URI (with its password) read from an secret; -> "[mg]" "{\"uri\": \"mongo_uri\", \"database\": \"marketplace\"}"; -> "[cols]" (mongodb collections [mg]); #3. Write: each product upserted by its sku, sold-out flag, discontinued removed; json parse_array "rx_products" "/items" "[p]" { json load "rx_p" [p]; mongodb put [mg] "partner_products" (json select "rx_p" "/sku") [p]; }; -> "[soldout]" (mongodb update [mg] "partner_products" "{\"stock\": 0}" "{\"available\": false}"); -> "[removed]" (mongodb delete_where [mg] "partner_products" "{\"status\": \"discontinued\"}"); #4. Read back the 5 most expensive available products, name and price only; -> "[top]" (mongodb find [mg] "partner_products" "{\"available\": {\"$ne\": false}}" "{\"sort\": {\"price\": -1}, \"fields\": {\"name\": 1, \"price\": 1, \"_id\": 0}, \"limit\": 5}"); -> "[stat]" (mongodb collection_info [mg] "partner_products"); #5. Confirm to the partner, to the legacy stock service on HTTP and to the old SOAP ERP; rest https_json_put "https://api.partner.example.com/v2/sync/acme" (json doc "rx_hdr") "[]" (concat "{\"synced\": " (json count "rx_products" "/items") ", \"sold_out\": " [soldout] "}"); rest http_json_put "http://stock.local:8080/api/sync" "{}" "[]" "{\"source\": \"partner\"}"; -> "[legacy]" (rest http "get" "http://stock.local:8080/api/status" "" "{}" "[]"); soap http "http://erp-legacy.local/ws/catalog.asmx" "{}" "SyncDone" "text/xml; charset=utf-8" (concat "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"><soap:Body><SyncDone xmlns=\"http://tempuri.org/\"><count>" (json count "rx_products" "/items") "</count></SyncDone></soap:Body></soap:Envelope>"); [top];
- For thousands of products, build the rows once and send them with
mongodb bulk(one round trip) instead of onemongodb putper product - Connections are pooled by the server: nothing to open or close, the same configuration reuses the same connection
Read supplier invoices from an Office 365 mailbox
Supplier invoices arrive as PDF attachments in a shared Office 365 mailbox. The script gets an OAuth token from Microsoft Entra ID, stores an IMAP connection with XOAUTH2 on the Invoices folder, downloads the unread mails of the suppliers to disk, moves them to Archive, and extracts the total of each PDF.
#1. OAuth token for IMAP; -> "[token]" (azure get_token "invoices@acme.onmicrosoft.com" (parameter get value "O365_INVOICES_PWD") "d61b48b2-5bee-4a2e-8ace-99f3c7603426" "076306e2-1bc8-4b4a-b69f-e35a53d4dd69" "[\"https://outlook.office365.com/IMAP.AccessAsUser.All\"]"); #2. IMAP connection: the token is the password, folder INBOX/Invoices; json load "rx_cm" (execute "mail.imap.config.get" "[hostname]" "outlook.office365.com" "[port]" "993" "[user]" "invoices@acme.onmicrosoft.com" "[password]" [token] "[auth]" false "[tls]" false "[ssl]" true "[connectTimeout]" "10000" "[sessionTimeout]" "60000" ); json iobject "rx_cm" "/" "xoauth2_scope" "1" STR; json iobject "rx_cm" "/" "inFolder" "INBOX/Invoices" STR; if (cm exist "rx_cm_imap_o365" "imap") {cm remove "rx_cm_imap_o365";}; cm set "rx_cm_imap_o365" (json doc "rx_cm"); #3. Unread mails of the suppliers with invoice in the subject, moved to Archive; json load "rx_state" (mail download imap_disk "tmp/rx_mail" 20 "unread" "Archive|Errors" false true "2026-10-01" null (mql {string ends_with [imap_from] "@supplier.example.com"}) (mql {string contains_ignore_case [imap_subject] "invoice"}) {cm get "rx_cm_imap_o365";}); #4. Total of each PDF saved in the download folder; -> "[dir]" (json select "rx_state" "/Directory"); json load "rx_out" "[]"; json load "rx_pdfs" (file dir_list_regex [dir] ".*\.pdf" true false); json parse_array "rx_pdfs" "/" "[f]" { -> "[total]" (string regexp_extract (pdf extract_text (concat [dir] "/" [f])) "Total[^0-9]*([0-9]+[.,][0-9]{2})" 1); json iarray "rx_out" "/" (concat "{\"file\": \"" [f] "\", \"total\": \"" [total] "\"}") OBJ; }; concat "{\"received\": " (json select "rx_state" "/NbReceived") ", \"invoices\": " (json doc "rx_out") ", \"connection_saved\": " (cm exist "rx_cm_imap_o365" "imap") "}";
- A classic mailbox without OAuth:
mail download pop3 <dir> <nb> <delete> <config>ormail download imap - Rotate the token: it expires after about one hour, call
azure get_tokenbefore each download
Health check of the outgoing mail queue
An administrator monitors the mails that MentDB sends in the background. The script reads the counters of the queue, checks that the SMTP connection used by the apps exists, reads the oldest error date only when there are errors, and returns a status for the monitoring tool.
#1. Counters of the queue; -> "[all]" (mail count_all); -> "[err]" (mail count_error); -> "[loaded]" (mail count_loaded); -> "[limit]" (mail process_limit); #2. Is the SMTP connection of the apps configured; -> "[smtp]" (cm exist "demo_cm_smtp" "smtp"); #3. The oldest error date exists only when there are errors; if (> [err] 0) {-> "[oldest]" (mail min_error_date);} {-> "[oldest]" "none";}; if (or (> [err] 0) (== [smtp] 0)) {-> "[status]" "WARNING";} {-> "[status]" "OK";}; concat "{\"status\": \"" [status] "\", \"queued_total\": " [all] ", \"in_error\": " [err] ", \"loaded\": " [loaded] ", \"sent_per_cycle\": " [limit] ", \"oldest_error\": \"" [oldest] "\", \"smtp_connection\": " [smtp] "}";
{"status": "WARNING", "queued_total": 0, "in_error": 0, "loaded": 0, "sent_per_cycle": 2, "oldest_error": "none", "smtp_connection": 0}- Replay the failed mails once the SMTP is fixed with
mail replay_error_all, or one withmail replay_error_id <id> - Read why a mail failed with
mail show_error 15andmail get_error <id>
Triage the mails in error and replay them
After an SMTP outage, dozens of mails are in error. The script lists them, reads the body and the SMTP error of the oldest one, replays all the mails of a connection when the credentials were the cause, deletes a mail refused by the recipient server, removes the mails of the test connection, and runs the queue now.
#1. Mails in error, with their id; json load "rx_errs" (mail show_error 15); -> "[n]" (json count "rx_errs" "/data"); -> "[id]" (json select "rx_errs" "/data/[0]/id"); #2. Body and SMTP error of the first one; -> "[body]" (string left (mail get_body [id]) 80); -> "[why]" (mail get_error [id]); #3. Bad credentials: fixed in the connection, replay all its mails. Refused recipient: delete the mail. Else replay it; if (string contains [why] "Username and Password not accepted") { mail replay_error_cm "demo_cm_smtp"; } { if (string contains [why] "550") {mail delete_error_id [id];} {mail replay_error_id [id];}; }; #4. Mails sent by the test connection are not replayed; mail delete_error_cm "rx_cm_smtp_test"; #5. Run the queue now and show the last mails; mail process; json load "rx_last" (mail show 5); concat "{\"errors_before\": " [n] ", \"errors_after\": " (mail count_error) ", \"first_subject\": \"" (json select "rx_errs" "/data/[0]/subject") "\", \"last_mails\": " (json count "rx_last" "/") "}";
- Replay or purge everything at once with
mail replay_error_allormail delete_error_all - Run the health check recipe before and after to follow the counters
Declare the legacy ERP databases: AS/400, DB2, Oracle, Firebird
An integration project must reach four legacy databases. Declare them with their config scripts (password from a private parameter), check the JDBC URL and the driver generated for each one, and that the scripts will find them by type, without opening any connection.
#1. One private secret for the read-only ERP account; parameter add "tuto_p4i_erp_pwd" "Erp-Read-2026!" "Password of the ERP read-only account" true; -> "[pwd]" (parameter get value "tuto_p4i_erp_pwd"); #2. The four databases, declared only; cm set "tuto_p4i_as400" {execute "db.as400.config.get" "[hostname]" "as400.erp.example.com" "[port]" "8471" "[database]" "ACMEPRD" "[user]" "MENTDB" "[password]" [pwd];}; cm set "tuto_p4i_db2" {execute "db.db2.config.get" "[hostname]" "db2.erp.example.com" "[port]" "50000" "[database]" "SALES" "[user]" "db2read" "[password]" [pwd];}; cm set "tuto_p4i_oracle" {execute "db.oracle.config.get" "[hostname]" "ora.erp.example.com" "[port]" "1521" "[database]" "FINPRD" "[user]" "fin_read" "[password]" [pwd];}; cm set "tuto_p4i_firebird" {execute "db.firebird.config.get" "[hostname]" "fb.shop.example.com" "[port]" "3050" "[database]" "/data/shop.fdb" "[user]" "SYSDBA" "[password]" [pwd];}; -> "[pwd]" ""; #3. What each config script produced, secrets left out; -> "[rep]" ""; json load "rx_p4i_all" (cm show_obj "db"); json parse_obj "rx_p4i_all" "/" "[k]" "[v]" { if (string starts_with [k] "tuto_p4i_") { json load "rx_p4i_cm" (cm get [k]); -> "[rep]" (concat [rep] (string replace [k] "tuto_p4i_" "") ": " (json select "rx_p4i_cm" "/subType") " | " (json select "rx_p4i_cm" "/driver") " | " (json select "rx_p4i_cm" "/jdbc") [_n_]); }; }; #4. Cleanup; -> "[rep]" (concat [rep] "Oracle as db: " (cm exist "tuto_p4i_oracle" "db") ", as sftp: " (cm exist "tuto_p4i_oracle" "sftp") ", password in report: " (string contains [rep] "Erp-Read")); json parse_obj "rx_p4i_all" "/" "[k]" "[v]" {if (string starts_with [k] "tuto_p4i_") {cm remove [k];};}; json unload "rx_p4i_all"; json unload "rx_p4i_cm"; parameter remove "tuto_p4i_erp_pwd"; [rep];
oracle: Oracle | oracle.jdbc.driver.OracleDriver | jdbc:oracle:thin:@ora.erp.example.com:1521:FINPRD db2: DB2 | com.ibm.db2.jcc.DB2Driver | jdbc:db2://db2.erp.example.com:50000/SALES as400: AS400 | com.ibm.as400.access.AS400JDBCDriver | jdbc:as400://as400.erp.example.com:8471/ACMEPRD firebird: Firebird | org.firebirdsql.jdbc.FBDriver | jdbc:firebirdsql://fb.shop.example.com:3050//data/shop.fdb Oracle as db: 1, as sftp: 0, password in report: 0
- Open one of them when the network allows it with
sql connectand{cm get "tuto_p4i_db2";}. - Check that the JDBC driver jar is in lib/ before the first connection.
- Compare the generated JDBC URL with the DBA documentation before going live.
Collect the orders sent by mail to a POP3 mailbox
Small customers still send their orders by mail to orders@. Download the new messages from the POP3 mailbox into a dated folder, delete them from the server once saved, and list the downloaded files for the order parser.
#1. The mailbox, SSL from the start on port 995; cm set "tuto_p4i_pop3" {execute "mail.pop3.config.get" "[hostname]" "pop.mail.example.com" "[port]" "995" "[user]" "orders@acme.example.com" "[password]" (parameter get value "tuto_p4i_pop3_pwd") "[tls]" false "[ssl]" true "[connectTimeout]" "10000" "[sessionTimeout]" "60000" ;}; #2. Download 20 messages at most, deleted from the server after the download; file mkdir "tmp/rx_p4i_pop3"; json load "rx_p4i_state" (mail download pop3 "tmp/rx_p4i_pop3" 20 true {cm get "tuto_p4i_pop3";} ); #3. Where are they; -> "[n]" (json select "rx_p4i_state" "/NbReceived"); -> "[dir]" (json select "rx_p4i_state" "/Directory"); #4. The files of this run; if (> [n] 0) { -> "[files]" (file dir_list [dir]); } { -> "[files]" "[]"; }; concat [n] " order mail(s) of " (json select "rx_p4i_state" "/Total") " bytes saved in " [dir] [_n_] [files];
- Prefer
mail download imapwhen the mailbox must keep the messages or use folders. - Parse each message and extract the order lines with
string regexp_extract. - Run it every 5 minutes with
job add.
IMAP: supplier confirmations only, as JSON, moved to a folder
Read only the unread mails whose subject contains 'Order confirmation' from the purchasing mailbox, save them as JSON (body and attachments in base64), move them to a Processed folder and decode the PDF attachments for the archive.
#1. The purchasing mailbox; cm set "tuto_p4i_imap" {execute "mail.imap.config.get" "[hostname]" "imap.mail.example.com" "[port]" "993" "[user]" "purchasing@acme.example.com" "[password]" (parameter get value "tuto_p4i_imap_pwd") "[auth]" false "[tls]" false "[ssl]" true "[connectTimeout]" "10000" "[sessionTimeout]" "60000" ;}; #2. 50 unread mails max, copied to Processed, marked as read, since the 1st of the month; json load "rx_p4i_state" (mail download imap "tmp/rx_p4i_imap" 50 "unread" "Processed" false true (date first_day_of_month (date sysdate)) null (mql (string ends_with [imap_from] "@ocean-pack.example.com")) (mql (string contains_ignore_case [imap_subject] "Order confirmation")) {cm get "tuto_p4i_imap";} ); #3. Each mail is a JSON file; -> "[saved]" 0; if (> (json select "rx_p4i_state" "/NbReceived") 0) { -> "[dir]" (json select "rx_p4i_state" "/Directory"); json load "rx_p4i_mails" (file dir_list [dir]); json parse_array "rx_p4i_mails" "/" "[m]" { if (string ends_with [m] ".json") { json load "rx_p4i_mail" (file load (concat [dir] "/" [m])); #4. Decode the PDF attachments: parts of type file; json parse_array "rx_p4i_mail" "/Parts" "[part]" { json load "rx_p4i_part" [part]; if (and (equal (json select "rx_p4i_part" "/type") "file") (string ends_with (string lower (json select "rx_p4i_part" "/filename")) ".pdf")) { file b64_write (json select "rx_p4i_part" "/content_b64") (concat "tmp/rx_p4i_imap_pdf/" (json select "rx_p4i_part" "/filename")); ++ "[saved]"; }; }; }; }; }; concat (json select "rx_p4i_state" "/NbReceived") " confirmation(s), " [saved] " PDF saved, still unread in the box: " (json select "rx_p4i_state" "/Unread");
- Use
mail download imap_diskto keep the original .eml files on disk. - Read Office 365 mailboxes with an OAuth token from
azure get_tokenas the password. - Check the order number of each PDF with
pdf extract_text.
Notify an internal HTTP webhook with a JSON event
When a stock level drops below the reorder point, push a JSON event to the warehouse system's internal webhook (plain HTTP inside the LAN) with an API key header, and log the answer for the support team.
#1. The event; json load "rx_p4i_evt" "{}"; json iobject "rx_p4i_evt" / "type" "stock.below_reorder_point" STR; json iobject "rx_p4i_evt" / "sku" "B-310" STR; json iobject "rx_p4i_evt" / "on_hand" 35 INT; json iobject "rx_p4i_evt" / "reorder_point" 81 INT; json iobject "rx_p4i_evt" / "at" (date systimestamp) STR; #2. Headers, the key comes from a private parameter; json load "rx_p4i_hdr" "{}"; json iobject "rx_p4i_hdr" / "Content-Type" "application/json" STR; json iobject "rx_p4i_hdr" / "X-Api-Key" (parameter get value "tuto_p4i_wms_key") STR; #3. POST to the webhook of the warehouse system; json load "rx_p4i_ans" (rest http_json_post "http://wms.lan.example.com:8085/hooks/stock" (json doc "rx_p4i_hdr") "[]" (json doc "rx_p4i_evt")); #4. Keep a trace; log write (concat "stock event " (json select "rx_p4i_evt" "/sku") " -> " (json doc "rx_p4i_ans")) "OK" "rx_p4i_wms" (json select "rx_p4i_evt" "/sku"); json doc "rx_p4i_ans";
- Use
rest https_json_postas soon as the webhook is published in HTTPS. - Sign the body with
string hmac_sha256and send the signature in a header. - Queue the events with the stack when the webhook is down.
Validate a payload, then patch it
Check an incoming JSON order against a JSON Schema, read the errors, fix them with a JSON Patch, check again, and keep the diff for the audit log.
-> "[schema]" "{\"type\": \"object\", \"required\": [\"id\", \"email\", \"lines\"], \"properties\": {\"id\": {\"type\": \"integer\"}, \"email\": {\"type\": \"string\", \"format\": \"email\"}, \"lines\": {\"type\": \"array\", \"minItems\": 1}}}"; -> "[doc]" "{\"id\": \"1042\", \"email\": \"ann@mail.com\", \"lines\": []}"; json load "rx_v" (json validate [doc] [schema]); -> "[res]" (concat "errors: " (json count "rx_v" "/errors") " (" (json select "rx_v" "/errors/[0]/path") " " (json select "rx_v" "/errors/[0]/message") ") | "); -> "[fixed]" (json patch [doc] "[{\"op\": \"replace\", \"path\": \"/id\", \"value\": 1042}, {\"op\": \"add\", \"path\": \"/lines/-\", \"value\": {\"sku\": \"A1\", \"qty\": 2}}]"); json load "rx_w" (json validate [fixed] [schema]); json load "rx_d" (json diff [doc] [fixed]); -> "[res]" (concat [res] "after the patch, valid: " (json select "rx_w" "/valid") " | " (json count "rx_d" /) " changes: " (json select "rx_d" "/[0]/op") " " (json select "rx_d" "/[0]/path")); json unload "rx_v"; json unload "rx_w"; json unload "rx_d"; [res]
errors: 2 (/id must be of type integer) | after the patch, valid: true | 2 changes: replace /id
json pathreads values with JSONPath: $.lines[?(@.qty > 1)].sku.json flattenturns a nested document into one column per value, ready for a CSV or Excel export.
Secure an internal API: sign a JWT, verify it, and see why a token is refused
Two services share a secret. The calling service signs a JWT (HS256) valid one hour with its subject and audience; the called service verifies the signature, the expiry and the audience. A token for another audience and a modified token are refused with their reason.
-> "[secret]" "change-me-to-a-secret-of-32-bytes-or-more"; #A fixed time (now) makes the recipe reproducible, without it the current time is used; -> "[tok]" (jwt sign "{\"sub\": \"billing-service\", \"aud\": \"orders-api\", \"scope\": \"orders:read\"}" [secret] "{\"expires_in\": 3600, \"now\": 1793750400}"); json load "rx_ok" (jwt verify [tok] [secret] "{\"audience\": \"orders-api\", \"now\": 1793752000}"); json load "rx_aud" (jwt verify [tok] [secret] "{\"audience\": \"admin-api\", \"now\": 1793752000}"); json load "rx_exp" (jwt verify [tok] [secret] "{\"audience\": \"orders-api\", \"now\": 1793760000}"); json load "rx_bad" (jwt verify (concat [tok] "x") [secret] "{\"now\": 1793752000}"); json load "rx_d" (jwt decode [tok]); -> "[res]" (concat "valid " (json select "rx_ok" "/valid") " for " (json select "rx_ok" "/claims/sub") " | other audience: " (json select "rx_aud" "/error") " | 3 hours later: " (json select "rx_exp" "/error") " | modified: " (json select "rx_bad" "/error") " | decoded scope " (json select "rx_d" "/claims/scope")); json unload "rx_ok"; json unload "rx_aud"; json unload "rx_exp"; json unload "rx_bad"; json unload "rx_d"; [res]
valid true for billing-service | other audience: the audience 'admin-api' is not in the token (aud: orders-api) | 3 hours later: the token expired at 1793754000 (now 1793760000) | modified: invalid signature | decoded scope orders:read
- Put the token in the header of the call: rest request "GET" "<url>" "{\"auth\": {\"bearer\": \"<token>\"}}".
- For tokens of an identity provider (Azure, Google, Keycloak), verify with its public keys: give the JWKS JSON ({"keys": [...]}) as the key.
Check orders against the OpenAPI document of a partner before sending them
A partner publishes the OpenAPI description of its API. Checking each request against it before the call turns a vague 400 Bad Request into a precise message (which field, which rule), and checking the answer catches a change of the partner early. The document is given inline here; in production it is usually a file.
-> "[spec]" "{\"openapi\": \"3.0.3\", \"info\": {\"title\": \"Partner orders\", \"version\": \"1.2.0\"}, \"servers\": [{\"url\": \"https://partner.example.test/api\"}], \"paths\": {\"/orders\": {\"post\": {\"operationId\": \"createOrder\", \"security\": [{\"key\": []}], \"requestBody\": {\"required\": true, \"content\": {\"application/json\": {\"schema\": {\"$ref\": \"#/components/schemas/Order\"}}}}, \"responses\": {\"201\": {\"description\": \"Created\", \"content\": {\"application/json\": {\"schema\": {\"type\": \"object\", \"required\": [\"id\", \"status\"], \"properties\": {\"id\": {\"type\": \"string\"}, \"status\": {\"type\": \"string\", \"enum\": [\"accepted\", \"pending\"]}}}}}}}}}}, \"components\": {\"securitySchemes\": {\"key\": {\"type\": \"apiKey\", \"in\": \"header\", \"name\": \"X-API-Key\"}}, \"schemas\": {\"Order\": {\"type\": \"object\", \"required\": [\"customer\", \"lines\"], \"additionalProperties\": false, \"properties\": {\"customer\": {\"type\": \"string\", \"minLength\": 1}, \"lines\": {\"type\": \"array\", \"minItems\": 1, \"items\": {\"type\": \"object\", \"required\": [\"sku\", \"quantity\"], \"properties\": {\"sku\": {\"type\": \"string\", \"pattern\": \"^[A-Z]{2}-[0-9]{4}$\"}, \"quantity\": {\"type\": \"integer\", \"minimum\": 1}}}}}}}}}"; json load "rec_ops" (openapi operations [spec]); -> "[op]" (json select "rec_ops" "/[0]/operation_id"); json unload "rec_ops"; -> "[good]" "{\"method\": \"POST\", \"path\": \"/api/orders\", \"headers\": {\"X-API-Key\": \"test-key\"}, \"body\": {\"customer\": \"ACME\", \"lines\": [{\"sku\": \"AB-1234\", \"quantity\": 2}]}}"; -> "[bad]" "{\"method\": \"POST\", \"path\": \"/api/orders\", \"headers\": {\"X-API-Key\": \"test-key\"}, \"body\": {\"customer\": \"ACME\", \"lines\": [{\"sku\": \"ab-12\", \"quantity\": 0}], \"comment\": \"urgent\"}}"; json load "rec_g" (openapi check_request [spec] [good]); -> "[good_ok]" (json select "rec_g" "/valid"); json unload "rec_g"; json load "rec_b" (openapi check_request [spec] [bad]); -> "[bad_count]" (json select "rec_b" "/error_count"); -> "[first]" (concat (json select "rec_b" "/errors/[0]/name") " " (json select "rec_b" "/errors/[0]/message")); json unload "rec_b"; -> "[answer]" "{\"method\": \"POST\", \"path\": \"/api/orders\", \"status\": 201, \"body\": {\"id\": \"O-981\", \"status\": \"shipped\"}}"; json load "rec_r" (openapi check_response [spec] [answer]); -> "[answer_error]" (json select "rec_r" "/errors/[0]/message"); json unload "rec_r"; -> "[res]" (concat "operation " [op] " | good order valid: " [good_ok] " | bad order: " [bad_count] " errors, first: " [first] " | answer: " [answer_error]); [res]
operation createOrder | good order valid: true | bad order: 3 errors, first: /lines/0/sku must match the pattern ^[A-Z]{2}-[0-9]{4}$ | answer: must be one of ["accepted", "pending"]- openapi resolve with a pointer shows the full schema of a body, with its $ref replaced, to write the mapping.
- Only local references are resolved: a document split into several files must be bundled first. No remote $ref is ever fetched.
