Consuming Your Own API

Logged in but treated as a guest? Nonces, apiFetch and rest_do_request for blocks, admin screens and PHP.

Same site, logged in โ€” and REST still treats you as a guest. Without a nonce, cookie authentication acts as if the request is unauthenticated: 401 rest_forbidden. This module shows the three ways to call your own API from inside WordPress.

CourseWordPress REST API Course ยท Module 6 of 9 ยท Stage 3 "Ship it"
Learnwp_create_nonce( 'wp_rest' ), X-WP-Nonce, apiFetch middlewares, rest_do_request(), expired nonces
HowReal code from 4WP FAQ and 4WP Booking, core code where our plugins do not use a function, interview questions after every lesson

Three ways in

flowchart LR
  F["fetch<br/>X-WP-Nonce"] --> API[("Your route")]
  AF["apiFetch<br/>nonce middleware"] --> API
  PHP["rest_do_request()<br/>no HTTP"] --> API
  classDef w fill:#ebf3fb,stroke:#61affe,color:#1e293b
  class F,AF,PHP w

Nonces expire: apiFetch fetches a fresh one and retries; with fetch, that is your job.

Before โ†’ after

BeforeAfter Module 6
401 for a logged-in adminX-WP-Nonce from wp_create_nonce( 'wp_rest' )
Hardcoded /wp-json/ in JSrest_url() localized from PHP
admin-ajax.php for new featuresyour REST route + apiFetch
HTTP request from PHP to the same siterest_do_request(), permissions still run

You'll be able to answer

  • Why does a logged-in user get 401 from the REST API without a nonce?
  • What do createNonceMiddleware and createRootURLMiddleware do?
  • When would you use rest_do_request()?