10. Learning REST APIs
Intro
-
Everyday we interact with apps and websites for various purposes, be it streaming new marvel TV show, searching for travel deals, scrolling through social media, one thing that’s common among all these is that they are pulling in information from the internet through REST APIs. So what is a REST API? That’s what we will see.
-
When you open a social media app, say on desktop, there is a header with some navigation options and a stream which updates continuously as we scroll down. The website itself is just a framework of templates for application. It provides us physical headers, the sidebars, the main content area, and skeleton for posts to be displayed.
-
When we visit the website, this entire framework is downloaded and runs in browser. It sends automated requests to representational state transferfer application programming interface or REST API for that service. REST API sends the data in JSON format and framework pulls the bits and pieces out and places it in the templates available to show the data that’s already present in browser.
-
When we reach at the end of the list, another REST request is sent, received and parsed. Using your smartphone ? No worries, the same REST request is sent, received and parsed in an application as well.
-
In a nutshell, REST APIs allow us to fully separate the presentation of the content from the content itself. It allows us to build lightning fast applications, that consume data rather than the entire pages, which leads to faster solutions and more scalable ones, and are ready for whatever changes we might incorporate in future. Knowing how REST APIs work and how to leverage their power, is the key to building powerful websites and web applications.
1. REST API: Representation State Transfer Application Programming Interface
01_01 The RESTful librarian
-
To make sense of what a REST API is and how it works, we will be making use of an librarian analogy. Imagine a library with books, a librarian and people who want to borrow, add, update or remove those books. On one side we have the clients, this is the web application, mobile app, or smartwatch, any interface that can be used to access data. On the other side we have the data store, where books and journals are kept. Typically data store is a database or a database server or some other type of server. In between client and data-store sits our librarian.
-
Librarian is the REST API, that receives, processes and handles requests and responses. When client submits a request, a
GET
request to get a resource, the REST API receives that request, identifies the requested resource, figures out what data needs to be gathered and in what format, creates a representation of the data which matches the requested format by the client, bundles it all up with the relevant response headers, containing metadata like the resource ID and hyperlinks to available actions, the media formats this response has, when the response was sent and other relevant information and sends it back to the client. Client gets the data, parses it into something meaningful on its end, while the REST API sits quietly waiting for the next request. -
Next, maybe client/user wants to change something,
PUT
, these changes are required in the content received in the previous response and sent back as a put request using the original ID. The REST API receives thePUT
request, recognizes this as a PUT request for an existing resource notes the requested resource’s media format, identifies the requested resource, converts the requested data into a media format that works for the data store, makes the changes submitted and returns the new representation of the resource along with success message to notify the client everything went as expected. -
Client makes the request, REST API receives the request, gathers and parses the data, and returns that data and response headers to the client.
01_02 What is a REST API?
-
You know the full form. REST APIs are integral to web app development and are becoming centerpiece of all web development. As per MDN, REST refers to a group of software architecture design constraints that bring about efficient, reliable and scalable systems. REST isn’t a specific technology but rather a data architecture and design methodology that produces consistent outputs and behaviors by receiving a set of standard methods called verbs and returning standardized structured data, typically JSON or XML, called the resource.
-
Representational State Transfer is a literal description of what’s happening. We transition between representations of states, and these representations are transformed back and forth between the application and the server.
-
Requesting for each new page when we browse a particular website is resource intensive and reuires a completed HTML document to be sent over the network, and document has to be written by a developer or generated by a content management system (CMS), before it is rendered and displayed in the browser.
-
Now imagine, instead of having a website made up of individual documents generated and downloaded from the server, we have a web application. An application downloaded to the browser runs in the browser and is populated with data from the web. In this application, each page is a view, representing the current state. When the visitor loads the website for the first time, all the components that make up the application are downloaded, including an HTML framework, reference items, one or more stylesheets, as JS.
-
The application then sends an URI (Universal Resource Identifier) request, for a web resource representing the next state of the application to be transferred and uses the resulting data to build the current view. When the visitor navigates from one view to another the application sendds a new URI request, for the web resource representing the next state of the application, which is transferred and used to add, modify, replace or delte previous data.
-
This representational transfer state is transferred as a data object not the entire new set of files. And the application can update its data without rendering the whole new page. This allows us to create so called single page applications (SPAs) for the web, and native applications for mobile devices and platforms that all use or consume the same REST resource.
-
E.g. When you visit Discord in your browser or smartphone, you are using 2 different applications to access the same data from the same REST resource.
-
All this request and response between client and server is controlled by an API. Defined as A set of features and rules that exist inside a software program enabling interaction between the software and other items, such as other software or hardware. In context of REST APIs, the API is the collection of tools used to access and work with the REST resources through verbs including GET, PULL, PUT and DELETE.
-
Think of REST resource as a librarian, and the API as the language used to talk to the librarian.
01_03 Sidebar: URI vs URL
- A Universal Resource Identifier (URI) is a compact sequence of characters that identifies an abstract or physical resource that provides a simple and extensible means for identifying a resource. URI is the most generic method for naming and locating a web resource.
-
Uniform Resource Locator (URL) is a subset of URI that identifies a resource and explains how to access that resource by providing an explicit method like
https://
orftp://
. -
All URLs are URIs, but not all URIs are URLs.
-
There is another subset of URI we don’t talk much about and these are URNs: Universal Resource Name. URN refers to both URIs under the URN scheme and to any other URI with the properties of a name. URN is a unique name identifier like name of a person. The URL provides the actual physical location of a resource. My URL right now would be Earth, India, Chhattisgarh, Raipur etc. On the web a URN can be either an explicit URN like
aws:s3:name:specification:requirements:data:xml:3.4.3
etc. or it can be a resource name such aslinkedin.com/instructors/instructor-name
. Finally, a URN can also be a URL, but doesn’t have to be always. -
A URL might also be a URN and both are URIs. In context of REST APIs, when we talk about the generic term URI to refer to how we access resources because within our code, we can use either URLs or URNs or a combination and URIs cover all the options.
01_04 The Six Constraints of REST
- There are 6 constraints of REST architecture, and to understand REST, we need to understand what these are, and why do they exist. Let’s get started:
1. Client Server Architecture:
- This constraint ensures proper separation of concerns. The client manages user interface concerns, while the server manages data storage concerns. In return we get a highly portable system where one REST service can serve many different clients and systems, without knowing or caring what those interfaces look like or what they are doing. We have a complete separation between the content data object and its presentation and interaction.
2. Statelessness
-
No client content, or information (AKA State), can be stored on the server between requests. The client is responsible for keeping track of its own session state, and all requests sent from a client must be self contained and complete. If the client session state is releavant, it must be sent along with a request, and if the server needs to store that state, it must pass it on to a database or similar service for a specific time.
-
E.g. The server can be asked to pass on an authentication token for a set period of time to allow authenticated requests.
3. Cacheability
- Cacheing as in storing responses for a set period of time, is an intricate part of web architecture and performance optimizations. All REST responses must be clearly marked as cacheable or not cacheable to ensure cacheing works as expected on the client side. This means cacheing responses that won’t change or are unlikely to change, cacheing rarely or periodically changed responses for reasonable periods of time, and blocking cacheing for constantly changing responses.
4. Layered System
- The system must be designed so that the client cannot know and doesn’t care whether it is directly connected to the server or to an intermediary like a CDN or mirror. This ensures scalability and also helps with security.
5. Code on Demand
- Servers are allowed to transfer executable code like client side JavaScript and compiled components to clients to extend and customize functionality. This is a less known use of rest.
6. Uniform Interface
- This breaks down further into four more constraints, so this is more of a primary constraint that has 4 more constraints within it.
6.1 Resource Identification in requests
-
A uniform resource must use resource identification in requests. In REST systems on the web, a URI is used to send a request and that URI will specify what resource it is that we are looking for and what format the response should use.
-
Key here is that, resource is the data sitting on the server, what REST returns is a representation of that resource which can have a different format from the server resource. So while the resource data may be stored as a table in SQL or BSON in MongoDB, the return representation maybe JSON or XML or even HTML. Next, a uniform interface.
6.2 Resource Manipulation Through Representations
- A uniform interface must allow, resource manipulation through representations. This means, once a client has a representation of a resource it can also modify or delete that resource. In other words, the client, given the right level of access, can control what’s stored on the server.
6.3 Self Descriptive Messages
- A uniform interface must issue, self-descriptive messages. This goes for both sending and receiving REST data. Each representation must describe its own data format. So if we are receiving JSON the response message will have its media type set to JSON. Without this information of data format, that data cannot be reliably parsed.
6.4 Hypermedia as the engine of application state (HATEOAS)
-
Complicated way of saying, once the client has access to a REST service, it should be able to discover all available resources and methods through the hyperlinks provided.
-
Once client requests a page resource, and along with the page contents return representation should include hyperlinks to all resources and methods available. In other words, the REST services describes its own use with every returned resource.
- If and only if a web-based API meets this six constraints, then only it can be considered as a RESTful API.
01_05 How REST relates to HTTP
-
Working with REST APIs we will most likely send our requests through HTTP. Does that mean REST and HTTP are intrinsically linked? No, but a large percentage of REST APIs area available through the web using HTTP protocol. So, although
not all REST APIs use the HTTP protocol
, the RESTful ones do. What this means basically: -
HTTP, HyperText Transfer Protocol is the protocol your web browser uses to access hypertext documents on the world wide web. That world wide web lives on the internet alongside other services such as SMTP for email, various messaging and video streaming services and so on.
-
REST is a set of six software architecture design constraints that produce a specific type of service. There is nothing in that defintion of REST that demands that service must run on HTTP and therefore the web.
-
One could just easily make a REST service running on FTP or SMTP or some other protocol. REST and HTTP are not linked, they are just a convenient pairing. When a
REST service runs on the web
, or HTTP to give us access to a web resource, we call it aRESTful API.
If you send a request through HTTP, to a REST service that meets the six constraints, that service is a RESTful API. The web is what makes REST as RESTful.
01_06 Who or what interacts with REST APIs?
-
In discussions related to REST APIs, we often hear developers talk about
clients who consume REST API.
-
Who are these clients, and what exactly are they consuming is the question!
-
A client in the scenario mentioned above, isn’t a human interacting with the website or app, rather it is the website or app itself. We are merely the operators of these REST clients, and the clients consume the REST API, by creating and sending requests, and receiving and parsing responses.
- The beauty of REST API is that, at its core, it doesn’t care who the client is as long as the client follows the rules while sending requests. REST API’s job is to receive requests, process data, and send responses. Where those requests come from, and where the responses go, is relatively irrelevant for the REST API. That means, if we have an open REST API, say for a public wordpress site. Once they have the access, the user can figure out how to access its methods and resources thanks to REST Constraints. Once they have that information, they can send valid requests to get access to REST API resources.
-
That’s the whole point of having a REST API to begin with. We provide an interface for our data to be consumed by whatever client comes asking for content. That doesn’t mean all REST APIs are completely open, or anyone can do anything they want with the data in REST API. Most REST APIs have strict limits on who can access what, which capabilities they are granted, and how many requests they can make in a set time period.
-
Social media sites are a great example of this. Twitter has several open REST APIs for a client. So an app to gain access to this API, the operator of that client, i.e. human being must first authenticate themselves with username and password, this ensures that twitter knowns who is using the REST API. Once access is granted, strict rate limits are imposed to ensure that the client doesn’t overuse the service. If you have used a third party client for social media tools, you might have seen warnings like API limit reached, or similar warnings.
-
Takeaway: We as human beings do not interact with REST API directly. Communication with REST API is handled by the client which can be anything really, a website, an app, an IoT device etc. The REST API
does not care
, it just receives requests, processes data, and sends responses and all our data is consumed by the REST client.
01_07 Tools to see REST API in action
-
Visit reqres. This is a public sandbox REST API. We want to send requests as regular REST client. This is a RESTful API that uses HTTP protocol for requests. We can use any client that uses http protocol to send in requests. We send our request on the address
https://reqres.in/api/users
. -
To make the response from a REST API readable, we need a REST client assigned for this purpose. Postman, Insomnia are some famous ones. If you have a favourite code editor, there is a good chance, there is a REST client extension or package for that editor as well. For VSCode there is an extension called
REST Client
from the marketplace. This is what we will be using to test out response, and create a human readable interface between ourselves and the REST-API. -
We have rest.http file and inside that after installing the VSCode Rest Client we will enter the REST API endpoint url and press
Ctrl+Alt+R
to display the response. Optionally, there is aSend Request
above the API endpoint, and you can click on that as well to send in your request, REST client will open a new tab on the side to display the response as shown below.
-
Response returned by REST Client is different from what you would get when you send the request through a browser, this is because this display contains the full REST response header with all the meta information about the response and it also formats the data to make it more readable.
-
In the next two sections, we will break down the request first and then the responses in details to understand how exactly all of this works and how to work with it in real life.
01_08 FAQs
- A RESTful API is a service that runs on the web over HTTP to facilitate access to web resources. TRUE ✅
- A representation of a resource is a unique copy of that resource, not the resource itself. TRUE ✅
- What is a REST API? An application programming interface that follows the six constraints of REST.
- What is the relationship between URIs, URLs, and URNs? A URN can be a URL, and both are always URIs.
- REST is a stateless protocol. What does this mean? No client context or information (aka “state”) can be stored on the server between requests.
- Who can interact with a REST API? Anyone, unless the REST API includes an authentication layer or similar access restrictions.
02. REQUEST In REST
02_01 Anatomy of a REST request
-
We will go over REST requests in detail in this section. We will see how requests are put together, what are the different pieces of a request, and how to use them. We will be needing a robust and well-built REST API to interact with. Wordpress provides one such REST API out of the box. We can follow along using any wordpress site, local or live on the web or any other REST resource. The concepts that we will be going over will be universal to all the REST APIs.
-
In its most basic form a REST request has two parts, a method and a URI. Method is one of the standard HTTP operators viz: GET, PUT, POST, PATCH, DELETE, OPTIONS, HEAD. URI points to the resource to interact with. Whether all of 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.
-
If we want a list of most recent posts on a wordpress site, we send a GET request to a resource URI for all posts.
-
When we submit our 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, as we need to send the actual data as well. Here the data structure on 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 POST’s resources through the same URI as before. We pass along authentication information to get access to that resource, declare the content type and then include the JSON data to be posted.
- Good thing is, we don’t have to normally type out these requests, and some of the metadata could be handled automatically. In a normal application, we use scripts to handle the requests and responses, most commonly some form of JavaScript.
02_02 Discovery
-
A key step in working with a REST API is
DISCOVERY.
This is the step where we figure out what resources and methods are available and what we can do with them. Ideally, a good REST API has extensive stand-alone documentation, providing all this information in human readable format, but world is not ideal, neither are REST APIs. So, even if no documentation is present the REST API will describe itself, thanks to the Hypermedia as the Engine of Application State constraint. Using theGET
andOPTIONS
verbs, we can figure out through the response of any API to find its resources and methods. -
For a simple REST API, the map might be a single level of resources URIs with GET methods. For a more complex REST API, like Wordpress REST API, there may be a complex tree of resources, each with its own methods that are documented within the response.
-
On running an options request to the posts resource, which gives us access to collection of all posts within a site we get the following:
-
POSTS resource has two core methods, get, which returns to us the most recent posts and post, which we can use to create new posts. Response from the options request, is enough to give all the information needed to send advanced requests and get the information you wanted, directly from the REST API.
-
Practically, discovery along with experimentation by developer is used to find the best resources and methods that help them accomplish their task in a most efficient manner, unless there is a documentation available, then you should refer that.
02_03 Resource and Representation
- The concept of REST was defined by Roy Fielding in a doctoral dissertation in 2000 called, Architectural Styles and the Design of Network Based Software Architectures. Here, we see a clear description of what a resource is.
-
In other words, any concept that might be the target of an author’s hypertext reference must fit within definition of a resource. A resource is a conceptual mapping to a set of entities, not the entity that corresponds to the mapping at any particular point of time. - Roy Fielding
-
Key here is
conceptual mapping
. Consider our librarian, when you submit a request to the librarian, you specify a resource to retrieve. This resource could be a book of red colour. Resource is that conceptual mapping. The details of the resource is used to retrieve the contents of the resource, and REST API doesn’t care what is inside of the resource. Resources can be collections or singletons. -
The structure of REST API makes it possible to narrow resource requests from collections to singletons, by increased specificity in the URI route.
-
The REST server generates a unique representation or copy of a book or resource for you when you request it, and can modify that representation to fit with your specifications. This is why a REST resource can serve up the same data, to multiple clients at the same time, and why a REST resource can serve up different variants of that data to different clients upon request.
-
The data may be stored as XML, but the representation of that data served to a client can be JSON or HTML or any other format that’s relevant. Resource is whatever data sits in the location we are pointint at, and the representation is the literal representation of the data we get when we access the resource.
02_04 Methods (Verbs)
-
A REST resource enables access to data but doesn’t in itself do anything with that data. To use a REST resource, we have to pass along instructions, about what action we want to perform. This is done using HTTP methods, also called
verbs
. -
Anytime we use a web browser, you or rather the browser uses HTTP methods to tell the server at the other end of the URL what type of request is being sent. By far the most common of these methods is
GET
. GET literally means GET whatever data is at the end of this address and send it to me. Anytime you visit a webpage or follow a link or click reload, forward or back or any other standard interaction in a browser, you are sending a get request over HTTP. -
The same goes for REST APIs. If we want to retrieve the data of resource, we send a GET request. This reques twill either return a 200, meaning Success, or 404 Not Found for Failure when there is nothing at the end of the resource or resource is invalid. Yes, that’s the 404 you get when you click a broken link, because internet on its own is a giant RESTful application.
-
GET is used to get data from a resource. To send data from client to the server we have three different methods, to perform different types of actions,
POST
,PUT
andPATCH
. Post is the most common of these methods, and is also the one used in regular non-REST scenarios like when you submit a form on a webpage. -
POST is used to create new resources and often subordinate resources of resource collections. Say you have a collection of products, and you want to add a new product, you send a post request along with the data for the new product in JSON format, and the REST API creates a new resource under the product’s resources and gives a new ID and resource URI.
-
A successful POST request returns a 201 create HTTP status along with a link to the new resource ID, in the response header. If you don’t have authorization to perform this action, you will get a 401 HTTP status, if resource exists then you will get a 409 conflict HTTP status, and if request is sent to a resource that doesn’t exist for some reason, in that case a 404 Not Found HTTP status is returned.
PUT
is used to update data at an existing singleton resource by replacing all of its contents with the contents of the new request based on ID. Posts just contains the contents, a PUT request contains the ID of the resource to update along with new content to be added or old content to be updated to that resource. If resource doesn’t exists then REST server may allow a new resource to be created with the user defined ID. A put request sent to the singleton resource will return 200 OK status on success, 204 on No Content present at the server or a 404 Not Found status if the ID is not found. If a PUT request is sent to the collection resource, a 405 Method Not Allowed status is returned, since Put updates an existing singleton resource.
-
PATCH
is used to modify an existing singleton resource based on ID. PUT updates the resources by replacing content, Patch can carry along instruction on how to modify the existing resources, without necessarily replacing everything. Patch returns the same status as Put. -
DELETE
does exactly what it sounds like. Delete the specified resource. Delete can only be used with singleton resources. If you try to delete a collection resource, you will get a 405 Method Not Allowed Status, because you should not be able to delete everything at once. -
There are 2 more methods, you might use from time to time, first is
OPTIONS
which returns a description of the communication options for the target resource and Head which returns just the head section of that response.
02_05 FAQs
- What is the minimum requirement to send a successful REST request? The request must contain a method (verb) and a URI.
- What is the correct verb to discover what methods are available for a specific REST resource? OPTIONS
- What is a “resource”? Any information that can be named can be a resource.
3. Response
03_01 Response Header
-
Anytime we send a request to an API, the API returns some form of response to tell us what happened on its end. This response comes in the form of a head section and whatever content the resource provided. This head section isn’t normally seen by us, but instead used by the client to handle the returned data. Every response from a REST API will have a head section and the contents of head will vary depending on the method you used and what kind of resources you requested.
-
To get just the head section of a response, we can send a head request to any resource. E.g.
HEAD https://www.villagevoice.com/wp-json/wp/v2/posts
-
We learn what protocol was used, and we get the HTTP status message, in case above
200 OK
. Head requests will only return 200 OK if we hit a resource that actually exists or 404 NOT FOUND if the URI was pointing at nothing. Type of server that delivered the content, date and time, and other details are conveyed to the client to figure out how to parse the data and perform next actions. -
Depending on the complexity of REST API and dataset it manages the response header will change. For our purposes most important part is HTTP status message at the very top.
03_02 HTTP Status Messages
- The HTTP response status codes at the top of the REST response header gives the client an immediate notification about the status of the request-response pair. The client uses these response codes, to identify success and failures and automatically respond with next steps. The HTTP response status codes are split into five main groupings.
Status Code | Meaning |
---|---|
1xx | Information |
2xx | Success |
3xx | Redirection |
4xx | Client Error |
5xx | Server Error |
-
Status codes of 100 format are rare and informational in nature. Mostly, these are used to inform the client about the status of the server, typically to wait for the server to finish so something like, I got your request, and I am processing it, hold on, sent by server to client or things like I have an open connection for you please send a request to the client from server. Generally, we don’t see 100 codes much at all.
-
Status codes of 200 format are success message, 200 meaning OK, 201 created, 204 No Content and so on.
-
Status Codes of 300 format indicate redirection. The client is provided with a new URL to follow to get to the resource. These codes include 301 for moved permanently, which tells the client to use the new URI for all future requests, 302/303 for found at this other url, there is also 307 for temporary redirect and 308 for permanent redirect. Important thing is if you are handling redirects in your client, or you are generating redirect messages when you build your own REST APIs, you have to account for all these different variants and figure out which one of these response codes you want to use to make things clear. Because unfortunately, the 300 response code set is quite confusing.
-
Status codes of 400 format, signal client error. 400 for bad request, i.e. the request is malformed or too large or similar, 401 meaning unauthorized, i.e. client lacks proper authentication to access the resource, 403 forbidden meaning the request is outright refused by the server, typically because the client is not logged in, or doesn’t have the correct permissions. 404 for not found, i.e. resource doesn’t exists in the first place and 405 meaning that method not allowed, this happens when you try to use a http verb like post on a resource that can only receive GET requests.
-
Status code of 500 formats signal server errors. 501 for internal server error, meaning something went wrong on the server end. 502 bad gateway meaning the server acts as a literal gateway or proxy and received an invalid response from whatever it is trying to connect to. The fairly common 503 service unavailable which is encountered when a server in overloaded or temporarily unavailable.
-
More on HTTP Status Codes Here
03_03 Request and Authorization/Authentication
-
The response you get from an API depeends on authorization level you have when you make the request. Most REST APIs provide leveled access, meaning all users can submit limited GET, HEAD and OPTIONS requests. Some users can submit POST requests, and a rare few users can submit PUT, PATCH and DELETE requests. To get a quick view of this, we can send two HEAD requests to the same resource, first an unauthenticated request, for this we will see that Allow header will only has GET option. When we send request with authorization we get allow header with GET, POST, PUT, PATCH, DELETE. Effectively this means that once you have provided the right authorization token in your request, you will have full control over the resource. Expires, Cache-Control and Keep-Alive are additional headers that tell the client for how long the credentials are valid, and when you might be kicked out and will have to provide authentication again and so on.
-
When interacting with the REST API in real world, including the wordpress REST API, we will typically encounter more robust authorization protocols like JSON Web Tokens
JWT
andOAuth2
that are encrypted and require multiple levels of authorization.
03_04 FAQs
-
An authorization header is used to change the authorization level of the currently logged in user.
False ❌
-
Who reads the response header? Primarily the client application, but anyone can read it.
-
A status message in the 400 range means: Client error
4. Request Response Pairs
04_01 Discovery using OPTIONS
- The first step in working with a REST API is discovery. For this we use an OPTIONS request. Post resource in wordpress is the collection for all the posts on the site, we can make a request in the following manner
OPTIONS https://www.villagevoice.com/wp-json/wp/v2/posts
. This gives us a default breakdown of all the methods and arguments available for this resource. But doesn’t give us any of the actual data. OPTIONS gives us all the options we have for a particular resource.
04_02 GET & 04_03 POST
-
To get the data from a resource we send a GET request. That means we want the data from the posts resource or the last 10 posts of a blog, we will send a GET request to the resource.
GET https://www.villagevoice.com/wp-json/wp/v2/posts
. What we get is a list of recent 10 posts on the site, each post is structures as a JSON object. It contains title, id, post data, content, link etc. If we want only 1 post we can send the argumentper_page=1
to get only 1 post. -
Supplied with necessary authorization, a REST API can be used to create new resources. We can use REST API to create new resource in case of WordPress API. This is done by sending a POST request to the resource collection like the posts collection inside of WordPress. To create a new post via the REST API, we send a POST request to posts resource.
POST https://www.villagevoice.com/wp-json/wp/v2/posts
Content-Type: application/json
{
"title": "A post created via the REST API",
"content": "This is the content of the post created with the REST API.",
"status": "publish",
"author": 1
}
- Everytime we send a POST request to a REST API, it will return the entire resource back to us, once it is created. That way, the client can then use that resource immediately for error checking to make sure everything worked properly and also just to populate the client itself, so the user of the client can see that post once it is created.
04_04 PUT/PATCH & 04_05 DELETE
-
We could either use POST, PUT or PATCH to make changes. We send options request first and then in methods header we see what all methods are allowed on the REST API. What’s different between a POST request for creation of resource and PUT request for updation of content is that we only send what we want to change in the update reqests, be it put or patch verb.
-
DELETE request only works only on singleton resources for the most part, because deleting everything at once just makes no sense in most of the cases and to err on the side of caution it’s better to be able to delete singleton resources at once because that’s what we will need for most of the time.
-
We need proper authorization header in the request sent for deletion, otherwise no deletion would occur. On success of DELETE request we will get 200 OK, and in the returned response we see that status changes to
"trash"
from publish. This is because that’s how WordPress works, when you delete a post it is moved to Trash Bin. -
REST API tries to mimic the behavior of the application you have access to. So, if WordPress puts deleted post through UI in a trash, then the REST API will also put the deleted post in trash. So how can one delete the post entirely? As in remove it and get it out of the database, where it no longer exists?
-
For that we need to ask the REST API by sending in OPTIONS request to the singleton resource we wish to delete. We will look at methods available for that singleton resource, on doing
Ctrl+F
on returned response we see that there is a force attribute to bypass trash and force deletion, by default it is false but we can pass it as true and get our desired result.DELETE https://www.villagevoice.com/wp-json/wp/v2/posts/15?force=true
will delete the post entirely and not just from trash. -
We will get a 200 OK and if you check the trash or send a get request to the singleton resource, you would get a 404 NOT FOUND.
04_06 FAQs
- PUT/PATCH always do the same thing. FALSE, depends on the REST API definition of the methods.
- Some requests get no response. This is a REST feature. FALSE
- What is the GET method used to do? Get the requested resource.
- What is the POST method used to do? Post a new resource with a unique ID on the REST server.
- When you submit a DELETE request, what happens? If the resource exists and you have the correct authorization, the resource is deleted or its status is changed on the server.