Working with the WordPress REST API
Learn to use the fetch API to interact with the WordPress REST API.
The WordPress REST API facilitates communication between applications and the WordPress server, providing access to the site’s data via a REST API. With this API, we can interact with WordPress data using programming languages beyond PHP. It allows us to send requests to the API using various modern programming languages and interpret the resulting data in JSON format. JSON, short for JavaScript Object Notation, is a data structuring format that presents data as an array of objects. These objects consist of key-value pairs, where attributes and their corresponding values are described. By utilizing the REST API, CRUD operations become accessible from any source, rather than being limited to theme or plugin PHP files.
Accessing the WordPress REST API
WordPress REST API consists of the URLs starting with /wp-json/wp/v2/. Data can be accessed by appending suitable elements called endpoints to this URL. For example, the endpoint to access blog posts is /posts.
Open the School of Excellence website and add /wp-json/wp/v2/posts at the end of the root URL. This returns the JSON data for the 10 most recent posts. We only have four posts in the database for now. The data is returned in JSON format. It is all squished and difficult to read but you can search for title to see the titles of the four posts. You can also send a GET request using the ThunderClient extension in VS Code to view the same data in a visually appealing manner.
Get hands-on with 1400+ tech skills courses.