-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtutorial.html
More file actions
2966 lines (2324 loc) · 139 KB
/
Copy pathtutorial.html
File metadata and controls
2966 lines (2324 loc) · 139 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Tutorial: Playwright API Testing from Scratch</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/atom-one-dark.min.css">
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
background: #ffffff;
color: #1f2328;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Helvetica, Arial, sans-serif;
line-height: 1.7;
padding: 40px 20px;
}
.container { max-width: 880px; margin: 0 auto; }
h1, h2, h3, h4 { color: #1f2328; margin-top: 2em; }
h1 { font-size: 2em; border-bottom: 1px solid #d0d7de; padding-bottom: 0.3em; }
h2 { font-size: 1.5em; border-bottom: 1px solid #d8dee4; padding-bottom: 0.2em; }
h3 { font-size: 1.25em; }
h4 { font-size: 1.1em; }
p { margin: 1em 0; }
ul, ol { padding-left: 1.5em; margin: 0.5em 0; }
li { margin: 0.3em 0; }
hr { border: none; border-top: 1px solid #d0d7de; margin: 2em 0; }
blockquote {
border-left: 4px solid #d0d7de;
padding: 0.5em 1em;
margin: 1em 0;
color: #656d76;
}
pre {
background: #1e1e1e !important;
border-radius: 6px;
padding: 16px;
overflow-x: auto;
margin: 1em 0;
}
pre code {
font: 14px/1.5 'Cascadia Code', 'Fira Code', 'Consolas', monospace;
background: none !important;
padding: 0 !important;
color: #d4d4d4;
}
code {
background: #f3f4f6;
padding: 0.2em 0.4em;
border-radius: 3px;
font-size: 0.9em;
color: #1f2328;
}
table {
border-collapse: collapse;
width: 100%;
margin: 1em 0;
}
th, td {
border: 1px solid #d0d7de;
padding: 8px 12px;
text-align: left;
}
th { background: #f6f8fa; color: #1f2328; }
a { color: #0969da; }
a:hover { text-decoration: underline; }
blockquote p { margin: 0.3em 0; }
</style>
</head>
<body>
<div class="container">
<h1>Tutorial: Playwright API Testing from Scratch</h1>
<p><strong>Target audience</strong>: Complete beginners — no Playwright, no TypeScript knowledge assumed.<br>
<strong>Format</strong>: Each lesson is thoroughly explained step by step, with every concept broken down so you understand not just what to type, but why it works.<br>
<strong>API under test</strong>: <a href="https://restful-booker.herokuapp.com">RESTful-Booker</a> — a free, public hotel booking API.</p>
<h2>Table of Contents</h2>
<table>
<thead>
<tr><th>Lesson</th><th>Topic</th><th>Time</th></tr>
</thead>
<tbody>
<tr><td>1</td><td>What is Playwright & API Testing?</td><td>15 min</td></tr>
<tr><td>2</td><td>Environment Setup</td><td>30 min</td></tr>
<tr><td>3</td><td>What Did That Command Create?</td><td>20 min</td></tr>
<tr><td>4</td><td>Your First API Test</td><td>45 min</td></tr>
<tr><td>5</td><td>API Test Runner Basics</td><td>30 min</td></tr>
<tr><td>6</td><td>Three Data Strategies</td><td>55 min</td></tr>
<tr><td>7</td><td>Validating Responses: Zod, Utilities & Assertions</td><td>55 min</td></tr>
<tr><td>8</td><td>API Object Model</td><td>60 min</td></tr>
<tr><td>9</td><td>Custom Fixtures & Environment Variables</td><td>35 min</td></tr>
<tr><td>10</td><td>API Mocking</td><td>45 min</td></tr>
<tr><td>11</td><td>Reporting, Config & CI/CD</td><td>45 min</td></tr>
<tr><td>12</td><td>Full Framework & Running Tests</td><td>30 min</td></tr>
<tr><td><strong>Total</strong></td><td></td><td><strong>~7.5 hours</strong></td></tr>
</tbody>
</table>
<hr>
<h2>Lesson 1 — What is Playwright & API Testing?</h2>
<p><strong>Time</strong>: 15 min</p>
<h3>What is Playwright?</h3>
<p>Playwright is an open-source automation framework developed by Microsoft. Most developers know it for <strong>browser automation</strong> — controlling Chrome, Firefox, or Safari programmatically to test web UIs. You can make it click buttons, fill forms, navigate pages, and verify that elements appear on screen.</p>
<p>But Playwright has a second, equally powerful capability built in: <strong>API testing</strong>. You can send raw HTTP requests (GET, POST, PUT, PATCH, DELETE) directly to a server <strong>without launching a browser at all</strong>. Playwright gives you a dedicated <code>request</code> object (called <code>APIRequestContext</code>) that acts as a full HTTP client, just like Postman or curl, but integrated directly into your test framework.</p>
<p>Official docs: <a href="https://playwright.dev/docs/api-testing">https://playwright.dev/docs/api-testing</a></p>
<h3>Why Automate API Tests?</h3>
<p>APIs are the backbone of modern applications. Every feature in a web or mobile app ultimately calls an API to fetch data, submit forms, or authenticate users. If the API breaks, the UI breaks too — no matter how polished the frontend is.</p>
<p>Here is why API testing matters:</p>
<ul>
<li><strong>Speed</strong> — API tests run in <strong>milliseconds</strong>. They send a request and check the response. There is no browser to launch, no CSS to render, no JavaScript to execute. A suite of 100 API tests can finish in under 30 seconds.</li>
<li><strong>Stability</strong> — UI tests are notoriously flaky. A button might not be clickable because an animation is still running. A locator might fail because a developer changed a CSS class. API tests have none of these problems — you send a structured request and check a structured response.</li>
<li><strong>Early feedback</strong> — API tests catch backend contract breaks before any UI tests even run. If the API changes its response format, you know about it in the first minute of your CI pipeline.</li>
<li><strong>Coverage</strong> — You can test edge cases that are hard to reach through the UI: sending invalid JSON, omitting required fields, testing authentication failures, etc.</li>
</ul>
<h3>What is Different from UI Testing?</h3>
<p>If you have used Playwright for UI testing, you are used to the <code>page</code> object — it represents a browser tab, and you call methods like <code>page.click()</code>, <code>page.fill()</code>, <code>page.goto()</code>.</p>
<p>API testing replaces <code>page</code> with <code>request</code>:</p>
<table>
<thead>
<tr><th>UI Testing</th><th>API Testing</th></tr>
</thead>
<tbody>
<tr><td><code>page</code> object (browser tab)</td><td><code>request</code> object (HTTP client)</td></tr>
<tr><td>Locators (<code>page.getByText()</code>)</td><td>URL paths (<code>/booking</code>)</td></tr>
<tr><td>Clicks and keystrokes</td><td>HTTP methods (GET, POST, PUT...)</td></tr>
<tr><td>Assert on DOM elements</td><td>Assert on JSON response bodies</td></tr>
<tr><td>Waits for rendering</td><td>Waits for HTTP response</td></tr>
<tr><td>Browser needed</td><td>No browser needed for pure API tests</td></tr>
</tbody>
</table>
<p><strong>Important</strong>: You still install a browser (Chromium) during setup because Playwright needs it internally for some utilities like HAR file recording/replay and context-level cookie handling. But the API tests themselves never open a browser window.</p>
<h3>What You Will Build</h3>
<p>By the end of this course, you will have a professional-grade API test framework with:</p>
<ul>
<li><strong>API Object Model</strong> — one client class per API domain (auth, booking). This is the API equivalent of Page Object Model (POM).</li>
<li><strong>Faker</strong> — randomized, realistic test data generation so every test run uses different data, preventing test-to-test interference.</li>
<li><strong>Zod</strong> — runtime schema validation for responses. Define the expected shape once, get both TypeScript types AND runtime checking.</li>
<li><strong>Three data strategies</strong> — static JSON (simple and debuggable), dynamic JSON templates (flexible placeholders), and Faker-generated (production-ready).</li>
<li><strong>Custom fixtures</strong> — automatic auth token injection so tests never need to think about authentication.</li>
<li><strong>API mocking</strong> — request interception and HAR file replay for offline testing.</li>
<li><strong>Allure reporting</strong> — rich, interactive test reports with timelines, graphs, and failure attachments.</li>
<li><strong>CI/CD (optional)</strong> — GitHub Actions and Jenkins configurations. Running locally is already a win.</li>
</ul>
<h3>The API Under Test: RESTful-Booker</h3>
<p>The API we will test throughout this tutorial is <a href="https://restful-booker.herokuapp.com">RESTful-Booker</a>, a free, publicly hosted hotel booking API. It supports:</p>
<ul>
<li><strong>Health check</strong> — <code>GET /ping</code> returns 201 if the API is alive</li>
<li><strong>Authentication</strong> — <code>POST /auth</code> returns a token for write operations</li>
<li><strong>Create Booking</strong> — <code>POST /booking</code> creates a new booking (no auth needed)</li>
<li><strong>Get Booking</strong> — <code>GET /booking/{id}</code> retrieves a single booking (no auth)</li>
<li><strong>Get Booking IDs</strong> — <code>GET /booking</code> lists all bookings, with optional name/date filters (no auth)</li>
<li><strong>Update Booking</strong> — <code>PUT /booking/{id}</code> replaces an entire booking (auth required)</li>
<li><strong>Partial Update</strong> — <code>PATCH /booking/{id}</code> updates specific fields only (auth required)</li>
<li><strong>Delete Booking</strong> — <code>DELETE /booking/{id}</code> removes a booking (auth required)</li>
</ul>
<p><strong>Official API documentation</strong>: RESTful-Booker provides a detailed <a href="https://restful-booker.herokuapp.com/apidoc/index.html">API documentation page</a> that lists every endpoint, its request/response schema, required headers, and example payloads. Keep this page open while following the tutorial — it is your reference for what each endpoint expects and returns.</p>
<p><strong>RESTful-Booker quirk</strong>: The server auto-clears all bookings periodically, so our tests will always create fresh data before reading/updating/deleting it. This is actually good practice — tests should own their test data.</p>
<hr>
<h2>Lesson 2 — Setting Up the Environment</h2>
<p><strong>Time</strong>: 30 min<br>
<strong>Install</strong>: Node.js, npm, VS Code or Cursor</p>
<h3>What is Node.js?</h3>
<p>Node.js is a <strong>JavaScript runtime</strong> — it lets you run JavaScript code on your computer (outside of a browser). Before Node.js, JavaScript could only run inside a web browser. Now it runs servers, command-line tools, and yes, test frameworks.</p>
<p>Playwright is a Node.js library. When you install Playwright, you are downloading JavaScript code that runs on Node.js.</p>
<p>When you run <code>npx playwright test</code>, Node.js loads the Playwright library, which then uses your operating system's networking APIs to send HTTP requests.</p>
<h3>What is npm?</h3>
<p>npm stands for <strong>Node Package Manager</strong>. It has two jobs:</p>
<ol>
<li>Download and install libraries (called "packages" or "dependencies") for your project</li>
<li>Manage which versions of those libraries your project uses</li>
</ol>
<p>When you run <code>npm install something</code>, npm:</p>
<ol>
<li>Contacts the npm registry (a massive online database of JavaScript libraries)</li>
<li>Downloads the library and its dependencies</li>
<li>Places them in a <code>node_modules/</code> folder in your project</li>
<li>Records the library name and version in <code>package.json</code></li>
</ol>
<h3>Install Node.js and npm</h3>
<p>If Node.js is not installed on your machine:</p>
<ol>
<li>Go to <a href="https://nodejs.org">https://nodejs.org</a></li>
<li>Download the <strong>LTS</strong> (Long Term Support) Windows installer (.msi) — LTS versions are stable and recommended for most users</li>
<li>Run the installer and leave all defaults checked</li>
<li><strong>Restart your terminal</strong> after installation so the new PATH environment variable takes effect (this lets your terminal find the <code>node</code> and <code>npm</code> commands)</li>
</ol>
<h3>Choose an Editor</h3>
<p>You need a code editor to write your test files:</p>
<ul>
<li><strong>VS Code</strong> — <a href="https://code.visualstudio.com">https://code.visualstudio.com</a>. Free, Microsoft-made editor with excellent TypeScript support.</li>
<li><strong>Cursor</strong> — <a href="https://www.cursor.com">https://www.cursor.com</a>. Built on VS Code with AI-assisted coding features.</li>
</ul>
<p>Either works fine for this tutorial. We will also install the <strong>Playwright Test for VS Code</strong> extension in Lesson 4.</p>
<h3>Verify Installation</h3>
<p>Open a <strong>new</strong> terminal window (PowerShell, CMD, or Git Bash) and run:</p>
<pre><code class="language-bash">node --version # Should show v20 or higher (e.g., v20.18.0)
npm --version # Should show 10 or higher (e.g., 10.9.0)
</code></pre>
<p>If these commands produce errors, Node.js was not installed correctly or the terminal was not restarted.</p>
<h3>Create the Project</h3>
<p>Create a new folder for the project and initialize Playwright inside it:</p>
<pre><code class="language-bash">mkdir playwright-api-testing
cd playwright-api-testing
npm init playwright@latest
</code></pre>
<p>The <code>npm init playwright@latest</code> command runs Playwright's scaffolding wizard. It asks a few questions:</p>
<ul>
<li><strong>TypeScript</strong>: Yes — TypeScript gives us type checking, better IDE autocomplete, and catches errors before running tests</li>
<li><strong>Tests folder</strong>: Keep the default <code>tests/</code></li>
<li><strong>GitHub Actions workflow</strong>: No — we will add CI/CD configuration manually in Lesson 11</li>
<li><strong>Install browsers</strong>: Yes — even though we are doing API tests, Playwright needs a browser installed for its internal utilities (mocking, HAR recording, etc.)</li>
</ul>
<p>After answering these questions, Playwright creates:</p>
<ul>
<li><code>package.json</code> — project manifest with Playwright as a dependency</li>
<li><code>playwright.config.ts</code> — central configuration</li>
<li><code>tests/</code> — a folder for test files (with an example spec)</li>
<li>A browser installation (Chromium) in a system cache</li>
</ul>
<h3>Install Additional Libraries</h3>
<p>Once the scaffold is complete, install the extra libraries that the framework will use:</p>
<pre><code class="language-bash">npm install -D @faker-js/faker zod dotenv allure-playwright allure-commandline
</code></pre>
<p>The <code>-D</code> flag saves them as <strong>devDependencies</strong> — libraries needed for development and testing but not for production.</p>
<p>Here is what each library does:</p>
<table>
<thead>
<tr><th>Library</th><th>Purpose</th><th>Why We Need It</th></tr>
</thead>
<tbody>
<tr><td><code>@faker-js/faker</code></td><td>Generates random test data</td><td>Creates realistic names, dates, prices, etc. for every test run</td></tr>
<tr><td><code>zod</code></td><td>Runtime schema validation</td><td>Checks that API responses have the correct fields and types</td></tr>
<tr><td><code>dotenv</code></td><td>Loads <code>.env</code> files into <code>process.env</code></td><td>Manages credentials and config without hardcoding</td></tr>
<tr><td><code>allure-playwright</code></td><td>Playwright reporter for Allure</td><td>Generates rich, interactive test reports</td></tr>
<tr><td><code>allure-commandline</code></td><td>CLI tool to serve Allure reports</td><td>Opens the Allure dashboard in your browser</td></tr>
</tbody>
</table>
<h3>What Just Happened?</h3>
<p>After the scaffold and the <code>npm install</code> command, this is your project structure:</p>
<pre><code>playwright-api-testing/
├── node_modules/ # Downloaded libraries (do not edit)
├── tests/ # Your test files go here
├── package.json # Lists all dependencies and scripts
├── playwright.config.ts # Central Playwright configuration
└── package-lock.json # Locks exact dependency versions
</code></pre>
<h3>Open in Your Editor</h3>
<ul>
<li>VS Code: <code>code .</code> (from the project folder)</li>
<li>Cursor: <code>cursor .</code> (from the project folder)</li>
</ul>
<p>You should see the folder structure in the editor's sidebar.</p>
<hr>
<h2>Lesson 3 — What Did That Command Create?</h2>
<p><strong>Time</strong>: 20 min</p>
<p>When you ran <code>npm init playwright@latest</code>, it generated several files and folders. Let us examine each one in detail.</p>
<h3><code>playwright.config.ts</code></h3>
<p>This is the most important file in the project after your test files themselves. It tells Playwright:</p>
<ol>
<li><strong>Where your tests are</strong> — the <code>testDir</code> option (default: <code>./tests</code>)</li>
<li><strong>Which tests to run</strong> — the <code>testMatch</code> pattern in each project</li>
<li><strong>What settings to use</strong> — base URL, headers, timeouts, retries</li>
<li><strong>What reporters to use</strong> — how to display results (HTML, list, JUnit, Allure)</li>
<li><strong>How to run tests</strong> — in parallel or serial, with how many workers</li>
</ol>
<p>A minimal config file looks like this:</p>
<pre><code class="language-ts">import { defineConfig } from '@playwright/test';
export default defineConfig({
testDir: './tests',
use: {
baseURL: 'https://restful-booker.herokuapp.com',
},
});
</code></pre>
<p>We will build on this config throughout the tutorial, adding reporters, projects, and environment variable loading.</p>
<h3><code>package.json</code></h3>
<p>This is the <strong>project manifest</strong>. It contains:</p>
<pre><code class="language-json">{
"name": "playwright-api-testing",
"version": "1.0.0",
"scripts": {},
"devDependencies": {
"@faker-js/faker": "^10.4.0",
"@playwright/test": "^1.60.0",
"allure-commandline": "^2.42.1",
"allure-playwright": "^3.9.0",
"dotenv": "^17.4.2",
"zod": "^4.4.3"
}
}
</code></pre>
<p>Key sections:</p>
<ul>
<li><strong><code>scripts</code></strong> — you can define custom commands here (e.g., <code>"test": "npx playwright test"</code>). We will leave it empty and use <code>npx playwright test</code> directly.</li>
<li><strong><code>devDependencies</code></strong> — all the libraries we installed. The <code>^</code> caret means "allow minor and patch updates." For example, <code>^10.4.0</code> means version 10.4.0 or any 10.x.x higher.</li>
<li><strong><code>type: "commonjs"</code></strong> — tells Node.js to use CommonJS module system (<code>require()</code> instead of <code>import</code>). Playwright handles TypeScript compilation internally, so this does not affect our <code>.ts</code> files.</li>
</ul>
<h3><code>node_modules/</code></h3>
<p>This folder contains all the downloaded libraries. It is generated by <code>npm install</code> and should <strong>never</strong> be edited manually. It is also the largest folder in the project (hundreds of megabytes). You should add it to <code>.gitignore</code>:</p>
<pre><code>node_modules/
</code></pre>
<p>Anyone cloning your project runs <code>npm install</code> or <code>npm ci</code> to recreate this folder.</p>
<h3><code>tests/</code></h3>
<p>This is where Playwright looks for test files by default. Playwright recognizes files with these patterns:</p>
<ul>
<li><code>*.spec.ts</code> — e.g., <code>healthcheck.spec.ts</code>, <code>create-booking.api.spec.ts</code></li>
<li><code>*.test.ts</code> — e.g., <code>booking.test.ts</code></li>
</ul>
<p>We will use <code>.api.spec.ts</code> as our naming convention (e.g., <code>ping.api.spec.ts</code>) and configure Playwright to only run files matching this pattern through our <code>api-tests</code> project.</p>
<h3><code>playwright-report/</code></h3>
<p>Created after you run tests (if the HTML reporter is enabled). Contains an HTML file with test results, including pass/fail status, durations, errors, and any attached files (like failed response bodies). View it with:</p>
<pre><code class="language-bash">npx playwright show-report
</code></pre>
<h3><code>.gitignore</code></h3>
<p>This file tells Git which files and folders to ignore (not commit to version control). Add these entries:</p>
<pre><code>node_modules/
/test-results/
/playwright-report/
/blob-report/
/playwright/.cache/
allure-results/
.env
hars/
</code></pre>
<p>Why ignore each?</p>
<table>
<thead>
<tr><th>Entry</th><th>Reason</th></tr>
</thead>
<tbody>
<tr><td><code>node_modules/</code></td><td>Recreated by <code>npm install</code> — hundreds of MB of libraries</td></tr>
<tr><td><code>/test-results/</code></td><td>Generated every test run — contains traces, screenshots, etc.</td></tr>
<tr><td><code>/playwright-report/</code></td><td>Generated every test run — HTML test report</td></tr>
<tr><td><code>/blob-report/</code></td><td>Generated when using blob reporter</td></tr>
<tr><td><code>/playwright/.cache/</code></td><td>Internal Playwright cache</td></tr>
<tr><td><code>allure-results/</code></td><td>Generated Allure report data</td></tr>
<tr><td><code>.env</code></td><td>Contains local secrets (credentials) — never commit!</td></tr>
<tr><td><code>hars/</code></td><td>Recorded API traffic files — personal to each developer</td></tr>
</tbody>
</table>
<h3><code>src/</code></h3>
<p>This folder does not exist yet — you will create it. It will hold your source code: API clients, Zod schemas, factory functions, custom fixtures, and utility helpers.</p>
<p>The final structure will look like:</p>
<pre><code>src/
├── api/
│ ├── auth/
│ │ ├── auth-client.ts
│ │ └── auth-schema.ts
│ ├── booking/
│ │ ├── booking-client.ts
│ │ ├── booking-schema.ts
│ │ └── booking-factory.ts
│ └── global/
│ └── global-setup.ts
├── fixtures/
│ └── api-fixture.ts
└── utils/
└── api-util.ts
</code></pre>
<hr>
<h2>Lesson 4 — Your First API Test</h2>
<p><strong>Time</strong>: 45 min</p>
<h3>The <code>request</code> Fixture</h3>
<p>In Playwright UI testing, every test receives a <code>page</code> object that represents a browser tab:</p>
<pre><code class="language-ts">test('ui test', async ({ page }) => {
await page.goto('https://example.com');
});
</code></pre>
<p>In API testing, you receive a <strong><code>request</code></strong> object — Playwright's <code>APIRequestContext</code>. It is a full HTTP client that can send GET, POST, PUT, PATCH, and DELETE requests.</p>
<pre><code class="language-ts">test('api test', async ({ request }) => {
const response = await request.get('https://api.example.com/endpoint');
});
</code></pre>
<p>The <code>request</code> fixture is <strong>built into Playwright</strong>. You do not need to create or configure it — Playwright gives it to you automatically when you list it as a test parameter.</p>
<blockquote>
<p><strong>Pro tip</strong>: Keep the <a href="https://restful-booker.herokuapp.com/apidoc/index.html">RESTful-Booker API docs</a> open in a browser tab. As you write each test, check the docs to see the exact request format, required headers, and expected response structure for each endpoint.</p>
</blockquote>
<h3>The Simplest API Test</h3>
<p>Create a new file <code>tests/ping.api.spec.ts</code> with the following content:</p>
<pre><code class="language-ts">import { test, expect } from '@playwright/test';
test('API is reachable', async ({ request }) => {
const response = await request.get('https://restful-booker.herokuapp.com/ping');
expect(response.status()).toBe(201);
});
</code></pre>
<p>Walk through this line by line:</p>
<ol>
<li><strong><code>import { test, expect } from '@playwright/test'</code></strong> — Imports Playwright's <code>test</code> function (to define test cases) and <code>expect</code> (to make assertions). These are the only two imports most tests need.</li>
<li><strong><code>test('API is reachable', async ({ request }) => { ... })</code></strong> — Defines a named test case. The <code>async</code> keyword is required because API calls are asynchronous. The <code>{ request }</code> destructures the <code>request</code> fixture from the test context — Playwright creates this fixture for you.</li>
<li><strong><code>const response = await request.get(...)</code></strong> — Sends an HTTP GET request to the specified URL. The <code>await</code> keyword pauses the test until the response arrives. Without <code>await</code>, the test would continue executing before the server responds.</li>
<li><strong><code>expect(response.status()).toBe(201)</code></strong> — Asserts that the HTTP status code equals 201. RESTful-Booker's <code>/ping</code> endpoint returns HTTP 201 (Created) rather than the more common 200 (OK) to indicate the service is alive.</li>
</ol>
<h3>Configuring baseURL</h3>
<p>Writing the full URL in every test is repetitive and fragile. If the API domain changes, you would need to update every test file.</p>
<p>Instead, set a <code>baseURL</code> in <code>playwright.config.ts</code>. Then all requests can use relative paths:</p>
<pre><code class="language-ts">import { defineConfig } from '@playwright/test';
export default defineConfig({
use: {
baseURL: 'https://restful-booker.herokuapp.com',
extraHTTPHeaders: {
'Content-Type': 'application/json',
Accept: 'application/json',
},
},
projects: [
{
name: 'api-tests',
testMatch: /.*\.api\.spec\.ts$/,
},
],
});
</code></pre>
<p>With this config:</p>
<ul>
<li><strong><code>baseURL</code></strong> — Every relative URL is resolved against this base. So <code>request.get('/ping')</code> becomes <code>GET https://restful-booker.herokuapp.com/ping</code>.</li>
<li><strong><code>extraHTTPHeaders</code></strong> — These headers are sent with <strong>every</strong> request automatically. <code>Content-Type: application/json</code> tells the server we are sending JSON. <code>Accept: application/json</code> tells the server we want JSON back. No need to repeat these in every request call.</li>
<li><strong><code>projects</code></strong> — Defines a project called <code>api-tests</code> that only runs files matching <code>*.api.spec.ts</code>. This isolates API tests from any UI tests you might add later.</li>
</ul>
<p>Now you can simplify the test:</p>
<pre><code class="language-ts">test('API is reachable', async ({ request }) => {
const response = await request.get('/ping');
expect(response.status()).toBe(201);
});
</code></pre>
<h3>Run the Test</h3>
<pre><code class="language-bash">npx playwright test --project=api-tests
</code></pre>
<p>Breaking this down:</p>
<ul>
<li><strong><code>npx</code></strong> — Executes a Node.js package without installing it globally. It looks for Playwright in <code>node_modules/.bin/</code>.</li>
<li><strong><code>playwright test</code></strong> — Invokes Playwright's test runner.</li>
<li><strong><code>--project=api-tests</code></strong> — Only runs tests matching the <code>api-tests</code> project configuration.</li>
</ul>
<p>If everything is set up correctly, you should see:</p>
<pre><code>Running 1 test using 1 worker
✓ 1 ping.api.spec.ts:3:1 › API is reachable (1.2s)
</code></pre>
<h3>The APIResponse Object</h3>
<p>Every Playwright request returns an <code>APIResponse</code> object with these key properties and methods:</p>
<pre><code class="language-ts">const response = await request.get('/booking');
response.status(); // HTTP status code (e.g., 200, 201, 403)
response.statusText(); // Status text (e.g., "OK", "Created", "Forbidden")
response.ok(); // true if status is between 200-299
response.headers(); // Object containing all response headers
response.json(); // Parses response body as JSON (returns a Promise)
response.text(); // Returns response body as plain text (returns a Promise)
response.url(); // The final URL after any redirects
</code></pre>
<h3>Read the Response Body</h3>
<p>Most API tests need to inspect the response body, not just the status code:</p>
<pre><code class="language-ts">test('get all booking IDs', async ({ request }) => {
const response = await request.get('/booking');
expect(response.status()).toBe(200);
const body = await response.json();
console.log(body); // Array of { bookingid: number }
});
</code></pre>
<p>The <code>response.json()</code> method reads the response body stream and parses it as JSON. It is <strong>asynchronous</strong> (returns a Promise), so you must <code>await</code> it.</p>
<p><strong>Important</strong>: You cannot call <code>response.json()</code> more than once on the same response. The response body is a stream — once read, it is consumed. If you need both the raw body and the parsed body, read it as text first:</p>
<pre><code class="language-ts">const text = await response.text();
const json = JSON.parse(text);
</code></pre>
<p>Or use the <code>getResponseDetails</code> utility we will build in Lesson 7, which handles this safely.</p>
<h3>Playwright VS Code Extension</h3>
<p>Install the <strong>Playwright Test for VS Code</strong> extension (by Microsoft) from the VS Code marketplace. It adds:</p>
<ul>
<li>A testing sidebar where you can see all tests</li>
<li>Run/debug buttons next to each test</li>
<li>A "pick locator" tool (useful for UI tests)</li>
<li>Failure output inline in the editor</li>
</ul>
<p>After installing, click the beaker icon in the VS Code sidebar to see the test explorer.</p>
<h3>Demo Task</h3>
<p>Create <code>tests/ping.api.spec.ts</code> with this content:</p>
<pre><code class="language-ts">import { test, expect } from '@playwright/test';
test('API is reachable', async ({ request }) => {
const response = await request.get('/ping');
expect(response.status()).toBe(201);
});
</code></pre>
<p>Run it:</p>
<pre><code class="language-bash">npx playwright test --project=api-tests
</code></pre>
<p>You should see a passing test. If it fails, check:</p>
<ol>
<li>Is the RESTful-Booker API reachable? Try <code>curl https://restful-booker.herokuapp.com/ping</code> in a terminal.</li>
<li>Is <code>baseURL</code> set correctly in the config?</li>
<li>Did you name the file with <code>.api.spec.ts</code>?</li>
</ol>
<hr>
<h2>Lesson 5 — API Test Runner Basics</h2>
<p><strong>Time</strong>: 30 min</p>
<h3>The <code>test()</code> Function</h3>
<p>Every test is defined by calling <code>test()</code> with a name and a function:</p>
<pre><code class="language-ts">test('create a booking', async ({ request }) => {
const response = await request.post('/booking', {
data: {
firstname: 'Alice',
lastname: 'Smith',
totalprice: 500,
depositpaid: true,
bookingdates: {
checkin: '2026-01-01',
checkout: '2026-01-05',
},
additionalneeds: 'breakfast',
},
});
expect(response.status()).toBe(200);
});
</code></pre>
<p>Key points about the <code>data</code> parameter:</p>
<ul>
<li>Playwright automatically serializes the JavaScript object to JSON (sets <code>Content-Type: application/json</code>)</li>
<li>Playwright sets the <code>Content-Length</code> header automatically</li>
<li>You do not need to call <code>JSON.stringify()</code> — Playwright handles it</li>
</ul>
<h3>Grouping Tests with <code>test.describe()</code></h3>
<p>Use <code>test.describe()</code> to organize related tests into a logical group:</p>
<pre><code class="language-ts">test.describe('Booking CRUD', () => {
test('create a booking', async ({ request }) => {
// ...create a booking...
});
test('get a booking', async ({ request }) => {
// ...retrieve a booking...
});
test('delete a booking', async ({ request }) => {
// ...delete a booking...
});
});
</code></pre>
<p>Benefits:</p>
<ul>
<li>Tests are visually grouped in the test runner output</li>
<li>You can apply configuration to the entire group (e.g., tags, retries)</li>
<li>The test output is indented under the describe block name</li>
</ul>
<h3>Understanding <code>async/await</code></h3>
<p>Every HTTP request in Playwright is <strong>asynchronous</strong> — it takes time for the request to travel to the server and the response to come back. JavaScript handles this with Promises and <code>async/await</code>.</p>
<p><strong>Without <code>await</code>, the test does not wait for the response:</strong></p>
<pre><code class="language-ts">// WRONG — the test passes immediately without waiting for the response
test('wrong', ({ request }) => {
request.get('/booking'); // fires but never awaited — test passes instantly
});
</code></pre>
<p>This test will always pass because it never actually checks the result.</p>
<p><strong>With <code>await</code>, the test pauses until the response arrives:</strong></p>
<pre><code class="language-ts">// RIGHT — the test waits for the response
test('right', async ({ request }) => {
const response = await request.get('/booking');
expect(response.status()).toBe(200);
});
</code></pre>
<p>Rules:</p>
<ul>
<li>Any function that uses <code>await</code> must be declared <code>async</code></li>
<li>Any function that calls an <code>async</code> function should either <code>await</code> it or use <code>.then()</code></li>
<li>Playwright request methods (<code>get()</code>, <code>post()</code>, <code>put()</code>, <code>patch()</code>, <code>delete()</code>) are all async</li>
<li><code>response.json()</code> and <code>response.text()</code> are also async</li>
</ul>
<h3>Basic Assertions with <code>expect()</code></h3>
<p>Playwright's <code>expect()</code> function provides matchers (assertion methods) that are specifically designed for testing:</p>
<pre><code class="language-ts">expect(response.status()).toBe(200); // Exact equality (===)
expect(response.ok()).toBeTruthy(); // Any truthy value
expect(response.statusText()).toBe('OK'); // Exact string match
expect(response.headers()['content-type'])
.toContain('application/json'); // String inclusion
</code></pre>
<p>For API testing, these are the most common assertions:</p>
<table>
<thead>
<tr><th>Matcher</th><th>What It Checks</th><th>Example</th></tr>
</thead>
<tbody>
<tr><td><code>.toBe(expected)</code></td><td>Exact equality (<code>===</code>)</td><td><code>expect(status).toBe(200)</code></td></tr>
<tr><td><code>.toEqual(expected)</code></td><td>Deep equality (recursive)</td><td><code>expect(body).toEqual({ id: 1, name: "Alice" })</code></td></tr>
<tr><td><code>.toMatchObject(expected)</code></td><td>Partial match (ignores extra fields)</td><td><code>expect(body).toMatchObject({ name: "Alice" })</code></td></tr>
<tr><td><code>.toBeTruthy()</code></td><td>Is truthy (not null/undefined/0/false)</td><td><code>expect(response.ok()).toBeTruthy()</code></td></tr>
<tr><td><code>.toBeOK()</code></td><td>Status is 200-299 (Playwright custom)</td><td><code>expect(response).toBeOK()</code></td></tr>
<tr><td><code>.toContain(item)</code></td><td>Array or string includes value</td><td><code>expect(text).toContain('json')</code></td></tr>
<tr><td><code>.toHaveProperty(key)</code></td><td>Object has property</td><td><code>expect(body).toHaveProperty('bookingid')</code></td></tr>
<tr><td><code>expect.any(type)</code></td><td>Is any value of given type</td><td><code>expect.any(Number)</code></td></tr>
<tr><td><code>expect.objectContaining(partial)</code></td><td>Object contains subset</td><td><code>expect.objectContaining({ name: 'Alice' })</code></td></tr>
</tbody>
</table>
<h3>Chaining Requests</h3>
<p>API tests often need to <strong>chain</strong> multiple requests. The most common pattern is: create data, capture the ID, then use that ID in subsequent requests.</p>
<pre><code class="language-ts">test('get created booking', async ({ request }) => {
// Step 1: Create a booking
const postRes = await request.post('/booking', {
data: {
firstname: 'Bob',
lastname: 'Brown',
totalprice: 300,
depositpaid: false,
bookingdates: {
checkin: '2026-02-01',
checkout: '2026-02-03',
},
},
});
const bookingId = (await postRes.json()).bookingid;
// Step 2: Get that booking using the ID from Step 1
const getRes = await request.get(`/booking/${bookingId}`);
expect(getRes.status()).toBe(200);
});
</code></pre>
<p>This pattern — <strong>POST to create, then use the returned ID</strong> — is the foundation of almost all API testing. You will see it used in every test file in this framework.</p>
<h3>Demo Task</h3>
<p>Create a file with 2 passing tests and 1 intentional failure to see how Playwright reports failures:</p>
<pre><code class="language-ts">// tests/demo.api.spec.ts
import { test, expect } from '@playwright/test';
test('passing test 1', async ({ request }) => {
const response = await request.get('/ping');
expect(response.status()).toBe(201);
});
test('passing test 2', async ({ request }) => {
const response = await request.get('/booking');
expect(response.status()).toBe(200);
});
test('intentional failure', async ({ request }) => {
const response = await request.get('/booking/99999999');
expect(response.status()).toBe(200); // This will fail — the booking does not exist
});
</code></pre>
<p>Run it:</p>
<pre><code class="language-bash">npx playwright test --project=api-tests
</code></pre>
<p>You will see:</p>
<ul>
<li><strong>3 passing tests</strong>: the 2 from <code>demo.api.spec.ts</code> plus the 1 from <code>ping.api.spec.ts</code> (which you created in Lesson 4)</li>
<li><strong>1 failure</strong>: the intentional failure in <code>demo.api.spec.ts</code></li>
<li>The actual status code (should be <strong>418</strong> — RESTful-Booker returns I'm a teapot for unknown bookings) vs the expected <strong>200</strong></li>
</ul>
<p>The <code>ping.api.spec.ts</code> test is included because our <code>api-tests</code> project matches all <code>*.api.spec.ts</code> files. From now on, every time you run tests with <code>--project=api-tests</code>, Playwright will execute <strong>every</strong> test across <strong>all</strong> <code>.api.spec.ts</code> files in the <code>tests/</code> folder.</p>
<hr>
<h2>Lesson 6 — Three Data Strategies</h2>
<p><strong>Time</strong>: 55 min<br>
<strong>Install</strong>: <code>@faker-js/faker</code> (already installed in Lesson 2)</p>
<p>Test data is the input you send to an API. Choosing how to provide it is one of the first decisions you make when building a framework. This project demonstrates three distinct strategies, each with its own trade-offs.</p>
<h3>Strategy 1: Static JSON Files</h3>
<p><strong>Best for</strong>: Known, repeatable scenarios. Debugging. Testing specific edge cases.</p>
<p>Static JSON files are exactly what they sound like — hardcoded JSON objects saved in <code>.json</code> files. The test imports the file and uses the data directly.</p>
<p><strong>Create <code>test-data/static-booking-data.json</code></strong>:</p>
<pre><code class="language-json">{
"validBooking": {
"firstname": "John",
"lastname": "Doe",
"totalprice": 1000,
"depositpaid": true,
"bookingdates": {
"checkin": "2026-12-31",
"checkout": "2027-01-01"
},
"additionalneeds": "Playwright API Test"
}
}
</code></pre>
<p><strong>Create the test</strong> — <code>tests/create-booking-static.spec.ts</code>:</p>
<pre><code class="language-ts">import { test, expect, APIResponse } from '@playwright/test';
import requestData from '../test-data/static-booking-data.json';
test('[POST] Create Booking using Static Data', async ({ request }, testInfo) => {
// Attach the request body to the test report for debugging
await testInfo.attach('REQUEST', {
body: JSON.stringify(requestData.validBooking, null, 2),
contentType: 'application/json',
});
const startTime = Date.now();
const response = await request.post('/booking', {
data: requestData.validBooking,
timeout: 10_000,
});
const duration = Date.now() - startTime;
// Inline helper to structure the response
async function getResponseDetails(method: string, response: APIResponse, duration: number) {
return {
url: response.url(),
method,
duration: `${duration}ms`,
status: response.status(),
statusText: response.statusText(),
headers: response.headers(),
body: await response.json(),
};
}
const responseDetails = await getResponseDetails('POST', response, duration);
// Attach the response to the test report
await testInfo.attach('RESPONSE', {
body: JSON.stringify(responseDetails, null, 2),
contentType: 'application/json',
});
test.step('Validation', async () => {
// Status code assertions
expect(response.status(), 'Status should be 200').toBe(200);
expect(response, 'Should be Success Status Code').toBeOK();
// Header assertion
expect(response.headers()['content-type']).toContain('application/json');
// Single property assertions
expect(responseDetails.body.booking.firstname).toBe(requestData.validBooking.firstname);
expect(responseDetails.body.booking.totalprice).toBe(requestData.validBooking.totalprice);
expect(responseDetails.body.booking.depositpaid).toBe(requestData.validBooking.depositpaid);
expect(responseDetails.body.booking.bookingdates).toHaveProperty('checkin');
expect(responseDetails.body.booking.bookingdates).toHaveProperty('checkout');
// Bulk property validation using toMatchObject
expect(responseDetails.body).toMatchObject({
bookingid: expect.any(Number),
booking: {
firstname: requestData.validBooking.firstname,
lastname: requestData.validBooking.lastname,
totalprice: requestData.validBooking.totalprice,
depositpaid: requestData.validBooking.depositpaid,
bookingdates: expect.objectContaining({
checkin: requestData.validBooking.bookingdates.checkin,
}),
additionalneeds: requestData.validBooking.additionalneeds,
},
});
});
});
</code></pre>
<p><strong>Why this approach matters</strong>: Notice we use <code>testInfo.attach()</code> to save both the REQUEST and RESPONSE to the HTML report. This means when you inspect a test failure, you can see exactly what was sent and what came back. The <code>test.step('Validation', ...)</code> block organizes assertions under a named step in the report.</p>
<p><strong>Pros</strong>: Simple, debuggable, no extra code needed.<br>
<strong>Cons</strong>: Same data every run — tests can interfere if they create duplicate records. Does not test "realistic" data variation.</p>
<h3>Strategy 2: Dynamic JSON Templates</h3>
<p><strong>Best for</strong>: Flexible scenarios where you want to control specific values while keeping the structure in a JSON file.</p>
<p>Instead of hardcoding every value, you create a <strong>template</strong> with <code>{0}</code>, <code>{1}</code>, <code>{2}</code>, etc. placeholders and replace them at runtime.</p>
<p><strong>Create <code>test-data/dynamic-booking-data.json</code></strong>:</p>
<pre><code class="language-json">{
"firstname": "{0}",
"lastname": "{1}",
"totalprice": "{2}",
"depositpaid": "{3}",
"bookingdates": {
"checkin": "{4}",
"checkout": "{5}"
},
"additionalneeds": "{6}"
}
</code></pre>
<p><strong>The <code>formatApiRequest</code> utility</strong> — <code>src/utils/api-util.ts</code>:</p>
<pre><code class="language-ts">export async function formatApiRequest(template: string, values: any[]): Promise<string> {
return template.replace(/"?\{(\d+)\}"?/g, (_match, p1) => {
const index = parseInt(p1, 10);
if (index >= values.length) return _match;
const value = values[index];
if (typeof value === 'number' || typeof value === 'boolean') return String(value);
return `"${value}"`;
});
}
</code></pre>
<p><strong>How the regex works</strong>: The pattern <code>"?\{(\d+)\}"?</code> matches:</p>
<ul>
<li>Optional double quotes <code>"?</code></li>
<li>An opening brace <code>\{</code></li>
<li>One or more digits <code>(\d+)</code> — this is captured as a group</li>
<li>A closing brace <code>\}</code></li>
<li>Optional double quotes <code>"?</code></li>
</ul>
<p>Numbers and booleans are returned without quotes (valid JSON requires <code>true</code>, not <code>"true"</code>). Strings are returned with quotes.</p>
<p><strong>Create the test</strong> — <code>tests/create-booking-dynamic.spec.ts</code>:</p>
<pre><code class="language-ts">import { test, expect, APIResponse } from '@playwright/test';
import { formatApiRequest } from '../src/utils/api-util';
import path from 'path';
import fs from 'fs';
test('[POST] Create Booking using Dynamic Data', async ({ request }, testInfo) => {
const filePath = path.join(__dirname, '../test-data/dynamic-booking-data.json');
const jsonTemplate = fs.readFileSync(filePath, 'utf-8');
const values = ['Mark', 'Miller', 1500, true, '2026-12-01', '2026-12-05', 'Massage'];
const requestString = await formatApiRequest(jsonTemplate, values);
const requestData = JSON.parse(requestString);
await testInfo.attach('REQUEST', {
body: requestString,
contentType: 'application/json',
});
const startTime = Date.now();
const response = await request.post('/booking', {
data: requestData,
timeout: 10_000,
});
const duration = Date.now() - startTime;
async function getResponseDetails(method: string, response: APIResponse, duration: number) {
return {
url: response.url(),