Skip to content
Tutorials Center
My learning

Topics

Lesson 46 of 68 ยท REST API, AJAX and Blocks

The REST API

Read WordPress content as JSON with the REST API: wp-json routes, _fields, _embed, filtering, pagination headers, authentication options and CORS basics.

Every WordPress site carries a built-in web API. Add /wp-json/ to the address and you get JSON that describes it; add /wp-json/wp/v2/posts and you get the latest posts as data instead of HTML. This is the REST API. The block editor uses it to load and save content, mobile apps use it, and you can use it from JavaScript on another site, a static site generator or a command-line script.

In this lesson you will learn how the URLs are organized, how to read posts and other content, how to trim and extend responses with _fields and _embed, how pagination is reported in response headers, and how authentication works. Building your own endpoints comes in Custom REST Endpoints. The requests below are shown as read-only curl commands because they need a real site; the TryIts re-create the response logic in plain PHP.

Routes and namespaces

A REST URL has three parts: the base, a namespace, and a route.

TEXT
https://example.com/wp-json/wp/v2/posts/42
                    |        |  |  |     |
                    base     |  |  |     post ID
                             |  |  route (collection)
                             |  version
                             namespace

The namespace wp/v2 belongs to core. Plugins add their own, such as acme/v1. The root, /wp-json/, lists every namespace and route on the site, so it is also the best documentation for what a particular site supports.

If pretty permalinks are off, the same API is available as /?rest_route=/wp/v2/posts.

The core collections you will use most:

Route Content
/wp/v2/posts Posts
/wp/v2/pages Pages
/wp/v2/media Media library items
/wp/v2/categories, /wp/v2/tags Terms of the built-in taxonomies
/wp/v2/users Users (public information only unless you are authenticated)
/wp/v2/comments Comments
/wp/v2/types, /wp/v2/taxonomies Descriptions of post types and taxonomies
/wp/v2/settings Site settings (needs authentication)

A custom post type shows up as its own route when you register it with show_in_rest => true, a flag you will meet in Custom Post Types.

Reading content

Terminal
# The latest posts (10 by default)
curl "https://example.com/wp-json/wp/v2/posts"

# One post by ID, and one by slug
curl "https://example.com/wp-json/wp/v2/posts/42"
curl "https://example.com/wp-json/wp/v2/posts?slug=hello-world"

# Search, filter by category ID, order oldest first
curl "https://example.com/wp-json/wp/v2/posts?search=api&categories=5&orderby=date&order=asc"

Each post is a JSON object with fields such as id, date, slug, status, link, title, content, excerpt, author, featured_media, categories and tags. Text fields are objects with a rendered key because they have already gone through filters like the_title and the_content. So the title text is at title.rendered, and the content is HTML.

Without authentication you only see published content. Draft and private posts are not returned, and the users route lists only people who have published posts and hides sensitive details such as email addresses. Asking for context=edit (the raw, editable version of fields) requires a logged-in user with the right capability.

Common query parameters for collections:

  • per_page (default 10, maximum 100) and page
  • search, slug, include, exclude
  • orderby and order
  • categories, tags, author, after, before (dates in ISO 8601)
  • _fields and _embed, described next

Trimming and extending responses

A full post object is large. When you need only a list of titles, ask for those fields:

Terminal
curl "https://example.com/wp-json/wp/v2/posts?_fields=id,link,title.rendered"

_fields takes a comma-separated list, and nested fields use dots. The server returns only those keys, which cuts the payload and speeds up the page that consumes it.

The opposite problem is that a post contains only IDs for its author, featured image and terms. To read those you would normally make more requests. _embed asks the server to include the linked resources in the same response, under an _embedded key:

Terminal
curl "https://example.com/wp-json/wp/v2/posts?_embed&_fields=id,title,_embedded"

Inside _embedded you will find author, wp:featuredmedia and wp:term arrays. Embedding saves round trips, but each embed costs the server extra queries, so use it for the things you will actually show. The _links property of each item lists the related URLs that _embed can follow.

flowchart LR
    C["Client"] -->|"GET /wp/v2/posts<br/>?_embed&_fields=..."| S["WordPress"]
    S --> Q["Query posts"]
    Q --> E["Load linked author,<br/>media and terms"]
    E --> F["Keep only requested fields"]
    F -->|"JSON + headers"| C

_embed adds linked resources; _fields removes keys you did not ask for.

Pagination headers

Collections are paged, and the paging details are in response headers, not in the JSON body:

Header Meaning
X-WP-Total Total number of matching items
X-WP-TotalPages Total number of pages at the current per_page
Link URLs for the prev and next pages when they exist
Terminal
curl -i "https://example.com/wp-json/wp/v2/posts?per_page=5&page=2"

Read the headers first and then request the pages you need. If you ask for a page beyond the last one, WordPress answers with an error (HTTP 400 and a code such as rest_post_invalid_page_number) instead of an empty list. Browsers hide custom response headers from cross-origin JavaScript unless the server lists them in Access-Control-Expose-Headers; WordPress does that for the total headers on REST requests, but check on your own site if a front end cannot read them.

The first TryIt builds a response for a list endpoint: it paginates a small dataset, sets the headers, builds the Link header and returns an error for a page that is too high. It is plain PHP written for this site, not WordPress's controller code.

PHP A list response with pagination headers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Notice that the middle page has both prev and next in its Link header, the last page has only prev, and the fourth request fails with a clear error code. A client loop therefore reads X-WP-TotalPages once and stops at that number.

Shaping the body: _fields in code

Now the same idea for _fields. The second TryIt applies a field list with dot notation to a post, mirroring what the real parameter does to the response. It also builds a tiny _embedded block so you can see why embedding is just "include the linked objects too".

PHP Filtering fields and embedding links

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The unknown path missing.key is simply ignored, which matches the forgiving way the real parameter behaves.

Authentication

Reading public content needs no credentials. Anything private, and every write (POST, PUT, DELETE), needs a logged-in user with the matching capability. Two methods cover most cases:

  • Cookie authentication with a nonce. Code running inside the dashboard or on your own front end is already logged in through the browser cookie. For safety against cross-site requests, WordPress also requires a nonce for the wp_rest action, sent in the X-WP-Nonce header (or a _wpnonce parameter). Without it, the request is treated as anonymous. You pass the nonce to your script with wp_localize_script() or wp_add_inline_script(); see Enqueuing Styles and Scripts.
  • Application passwords. Since WordPress 5.6 each user can create revocable passwords for external programs in their profile. The client sends them with HTTP Basic authentication (username:application-password). This is the simplest way for a script or another server to call the API, and it should only be used over HTTPS.
Terminal
# Create a post from a script, authenticated with an application password
curl -X POST "https://example.com/wp-json/wp/v2/posts" \
  --user "editor:abcd efgh ijkl mnop qrst uvwx" \
  --header "Content-Type: application/json" \
  --data '{"title":"From curl","status":"draft"}'

Plugins can add other schemes (OAuth, JWT), but those are not part of core. Whatever the method, the user's capabilities still decide what succeeds: a contributor cannot publish, no matter how they authenticate.

CORS in one paragraph

Browsers block JavaScript on one origin from reading responses from another unless the server allows it through CORS headers. Core WordPress answers REST requests with CORS headers and handles the preflight OPTIONS request, so simple reads of public data from another site generally work. Credentials are the hard part: cookies are tied to your own site, so a different origin cannot use cookie authentication. For cross-origin writes, use application passwords or a token scheme, and customize the allowed origins and headers with the REST filters (such as rest_allowed_cors_headers) rather than editing core.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Where does WordPress report the total number of matching items for a REST collection?

    Totals are sent in the X-WP-Total and X-WP-TotalPages headers, and the Link header holds prev/next URLs.
  2. 2. Which query string returns only the ID and the rendered title of each post?

    _fields takes a comma-separated list and supports dot notation for nested values such as title.rendered.
  3. 3. What does _embed do?

    _embed adds an _embedded property with the resources the item links to, saving extra requests.
  4. 4. A script on another server needs to create a draft post. Which authentication method fits best?

    Application passwords are built for external programs. Unauthenticated requests cannot write, and salts are secrets that must never leave the server.

Summary

  • The REST API lives at /wp-json/; core routes are under /wp/v2/, and plugins add their own namespaces.
  • Collections accept per_page, page, search, orderby, order and filters by term, author and date.
  • _fields trims the response and _embed includes linked resources; each has a cost or a benefit worth measuring.
  • Totals and page links are in the X-WP-Total, X-WP-TotalPages and Link headers; a page past the end is an error.
  • Public reads need no login; writes need cookie authentication with an X-WP-Nonce header or an application password.
  • Capabilities still apply to every authenticated request.

Next: Custom REST Endpoints.