Join Morten Rand-Hendriksen for an in-depth discussion in this video Anatomy of a REST request, part of Learning REST APIs.
- In this chapter, we'll look at REST requests in detail, how they're put together, what the different pieces are, and how to use them. To do this, we first need a robust and well-built REST API to interact with and WordPress provides such a REST API out of the box so for this chapter, I'll use a locally installed version of WordPress running under the domain restful.dev to demonstrate. If you want to, you can follow along using any WordPress site, local or live, on the web or any other REST resource. The principles taught here are universal to all REST APIs, which is the whole point of REST APIs.
Let's start with the anatomy of a REST request. In its most basic form, a REST request has two parts, a method and a URI. The method is one of the standard HTTP operators, get, post, put, patch, delete, options, and head, and the URI points to the resource we want it to interact it. Whether all these listed methods work on the resource at the end of the provided URI depends on the configuration of the REST API and the authorized capabilities of the current user.
So if we want a list of the most recent posts on a WordPress site, we send a GET request to the resource URI for all posts, GET site.com/wp-json/wp/v2/posts. When we submit a request, we can also send along metadata in the request header. This data should include the content type to comply with the self-descriptive messages constraints and can also contain a user agent string, accepted language string, authentication, cache control and more.
If we want to send information to the REST API to create a new entry or update an existing one, the request gets more complex because we have to send along the actual data. Here, the data structure of the request needs to match the content type defined in the request. So in this example, the content type is set to application/json, meaning the data has to be marked up as JSON as well. To create a new post through the WordPress REST API, we send a POST request to the post's resource through the same URI as before.
Using jQuery AJAX, the POST request would look like this. Here, we do the same thing, define a URI, send a POST request to it, append some data and on success, capture the response to be logged in the console.
- What is a REST API?
- Who or what interacts with REST APIs?
- Anatomy of a REST request
- HTTP status messages
- Request/response pairs
- GET, POST, and DELETE