CRUD is an acronym for Create, Read, Update, and Delete. Each of those operations can be done using API request methods:
-
POST: Create record on the API resource
-
GET: Read the record from the API resource
-
PUT: Update the existing record on the API resource
-
DELETE: Self-explanatory, this method deletes the record from API resource
Now let's review those operations one by one in Playwright.
Here is an example of a POST request in Playwright to create a new Article in the
Conduit application. To interact with API, we use a separate API URL for this test application.
-
Keep in mind
The application URL and API URL are often two different URLs. You can't open the API URL in the web browser as well as you can't send API request to application URL.
Notice that we use a request fixture, passed as an argument to the test. This fixture gives us access to API request methods
We call post() method to make a POST request. We pass 3 arguments: API URL, Request object, and Headers.
-
The API URL is passed as a string
-
Request object is passed under data property and should be a valid JSON object
-
API request headers are passed under headers property and also should be a JSON object
When the API request is completed, the value has to be assigned to some constant or variable. Then to extract the JSON response object from the response, need to call a json() method as shown in the line 15.
-
Caution
It's important not to forget using the method await before calling Playwright commands. Otherwise, the code will not work properly.
After the response object is received, you can perform a validation using build in expect() method to validate JSON properties of the object or validate the status code.
The simplest API request. Just read the information from API resource. Here is the code example that you can execute on your computer:
In this test, we request the list of available tags for our test application. When it should be a secure API request, you can additionally pass the headers object with the Authorization token, as shown in the example above for the POST request.
PUT request is used when you need to update the existing record on the API resource. For example, the code below will update the article title, which was created in the first example by the POST request.
To update the article, we append the Article ID to the request URL. This way we tell our API, which article we want to update. Then for this request we use put() method and provide new request object with updated title for the article.
DELETE request method performs the deletion of the resource on the API. Very straightforward. Just provide the ID of the resource to delete and make a request. Here is the example:
-
Best Practice
It's considered best practice to perform a GET request after the Delete request to properly validate the deletion of the resource