Download as pdf or txt
Download as pdf or txt
You are on page 1of 70

Postman for API Testing: A Beginner's

Guide: Learn to test APIs like a pro with


Postman with Real-World Examples
and Step-by-Step Guidance Parvin
Visit to download the full and correct content document:
https://ebookmass.com/product/postman-for-api-testing-a-beginners-guide-learn-to-te
st-apis-like-a-pro-with-postman-with-real-world-examples-and-step-by-step-guidance-
parvin/
More products digital (pdf, epub, mobi) instant
download maybe you interests ...

Web API Development for the Absolute Beginner: A Step-


by-step Approach to Learning the Fundamentals of Web
API Development with .NET 7 1st Edition Irina Dominte

https://ebookmass.com/product/web-api-development-for-the-
absolute-beginner-a-step-by-step-approach-to-learning-the-
fundamentals-of-web-api-development-with-net-7-1st-edition-irina-
dominte/

The Absolute Beginner's Guide to HTML and CSS: A Step-


by-Step Guide with Examples and Lab Exercises 1st
Edition Kevin Wilson

https://ebookmass.com/product/the-absolute-beginners-guide-to-
html-and-css-a-step-by-step-guide-with-examples-and-lab-
exercises-1st-edition-kevin-wilson/

Game Theory: An Introduction with Step-by-Step Examples


Ana Espinola-Arredondo

https://ebookmass.com/product/game-theory-an-introduction-with-
step-by-step-examples-ana-espinola-arredondo/

Cashed Up with Commercial Property: A Step-by-Step


Guide to Building a Cash Flow Positive Portfolio Helen
Tarrant

https://ebookmass.com/product/cashed-up-with-commercial-property-
a-step-by-step-guide-to-building-a-cash-flow-positive-portfolio-
helen-tarrant/
Learn Programming with C: An Easy Step-by-Step Self-
Practice Book for Learning C 1st Edition Imran

https://ebookmass.com/product/learn-programming-with-c-an-easy-
step-by-step-self-practice-book-for-learning-c-1st-edition-imran/

Python Programming for Beginners: 2 Books in 1 - the


Ultimate Step-By-Step Guide to Learn Python Programming
Quickly With Practical Exercises Mark Reed

https://ebookmass.com/product/python-programming-for-
beginners-2-books-in-1-the-ultimate-step-by-step-guide-to-learn-
python-programming-quickly-with-practical-exercises-mark-reed/

Integrated Behavioral Health in Primary Care: Step-By-


Step Guidance for Assessment and Intervention

https://ebookmass.com/product/integrated-behavioral-health-in-
primary-care-step-by-step-guidance-for-assessment-and-
intervention/

Academic Conference Presentations: A Step-by-Step Guide


Mark R. Freiermuth

https://ebookmass.com/product/academic-conference-presentations-
a-step-by-step-guide-mark-r-freiermuth/

Python Programming: 3 Books in 1: Ultimate


Beginneru2019s, Intermediate & Advanced Guide to Learn
Python Step-by-Step

https://ebookmass.com/product/python-programming-3-books-
in-1-ultimate-beginners-intermediate-advanced-guide-to-learn-
python-step-by-step/
Contents Guide
~ Welcome & What You’ll Learn

Section 1: Introduction to Postman and API Testing


1. Exploring Postman: A Primer
2. Unveiling Postman's Core Features
3. Initiating Your First API Request: Basics Unraveled
4. Crafting Your Initial API Request: A Step-by-Step Guide
5. Mastering API Requests: Practical Implementation Tips
Section 2: CRUD Operations with Postman
6. Creating a POST Request: Dive into Data Transmission
7. POST Requests Demystified: Advanced Techniques
8. Managing Resources: Understanding PUT & PATCH Requests
9. Enhancing Resource Updates: Advanced PUT & PATCH Tactics
10. Deletion Simplified: The DELETE Request Unveiled
Section 3: Organizing with Collections
11. Harnessing the Power of Collections: Overview and Benefits
12. Building Your First Collection: Structuring Your Workflows
Section 4: Harnessing Variables
13. Variable Mastery: From Creation to Implementation
14. Leveraging Variables: Advanced Strategies
15. Scripting Variables: Introduction and Setup
16. Advanced Variable Scripting: Optimization and Efficiency
17. Dynamic Variable Handling: Advanced Techniques
Section 5: Maximizing Environments
18. Building Environments: Foundations and Best Practices
19. Environmental Optimization: Advanced Configuration Techniques
20. Environment Management: Strategies for Efficiency and Scalability
Section 6: Crafting Test Scripts
21. Scripting Simplified: Quick Creation Techniques
22. Initiating Your First Test: A Hands-On Approach
Section 7: Effective Debugging Strategies
23. Debugging Decoded: Practical Techniques for Troubleshooting, Part 1
24. Debugging Decoded: Practical Techniques for Troubleshooting, Part 2
Section 8: Harnessing Data for Testing
25. Unleashing the Power of Data: Integrating CSV & JSON Files, Part 1
26. Unleashing the Power of Data: Integrating CSV & JSON Files, Part 2
27. Unleashing the Power of Data: Integrating CSV & JSON Files, Part 3
28. Unleashing the Power of Data: Integrating CSV & JSON Files, Part 4
Section 9: Mastering Authorization
29. Integrating Authorization: In-Depth Exploration, Part 1
30. Integrating Authorization: In-Depth Exploration, Part 2
31. Demystifying Authorization: Understanding Its Role in API Requests
Section 10: Automation with Command Line and CI/CD Integration
32. Command-Line Automation: Streamlining with Newman, Part 1
33. Command-Line Automation: Streamlining with Newman, Part 2
34. CI/CD Integration: Seamless Execution with Jenkins
Section 11: Workspace Management, Monitoring, and Documentation
35. Workspace Wonders: Creating and Managing Workspaces, Part 1
36. Workspace Wonders: Creating and Managing Workspaces, Part 2
37. Monitoring Magic: Implementing API Monitors, Part 1
38. Monitoring Magic: Implementing API Monitors, Part 2
39. Documentation Delight: Crafting Comprehensive API Documentation, Part 1
40. Documentation Delight: Crafting Comprehensive API Documentation, Part 2
Section 12: Remote Execution
41. Embracing Remote Execution: Unleashing the Power of URL Deployment, Part 1
42. Embracing Remote Execution: Unleashing the Power of URL Deployment, Part 2
Section 13: Exploring SOAP API Testing
43. Navigating SOAP Requests: Mastering Postman's SOAP Capabilities, Part 1
44. Navigating SOAP Requests: Mastering Postman's SOAP Capabilities, Part 2
Section 14: Advanced API Chaining Techniques
45. Building Seamless Connections: API Chaining Essentials, Part 1
46. Building Seamless Connections: API Chaining Essentials, Part 2
47. Building Seamless Connections: API Chaining Essentials, Part 3
48. Building Seamless Connections: API Chaining Essentials, Part 4
Section 15: Unveiling Mock APIs
49. Demystifying Mock APIs: Understanding Their Purpose and Utility
50. Crafting Mock APIs: Practical Implementation in Postman

~ Conclusion
Welcome & What You’ll Learn
Welcome fellow explorer, to the exciting world of API testing! If you’re
building applications, websites, or any system that interacts with other
programs online, understanding how to test APIs is a superpower. This book
is your comprehensive guide to mastering Postman, the go-to tool for
testing APIs like a seasoned professional.
What Exactly Are APIs?
APIs are the communication bridges of the digital world. Let’s break that
down:
● API stands for Application Programming Interface. Think of it
like a restaurant menu—it lists available ‘dishes’ (data or functions)
and helps you order them. Websites, mobile apps, or smart devices
use APIs to ‘order’ data or request actions from other systems.
Why API Testing?
Imagine you built a super-cool robot and want to make sure all its parts
work together. That’s precisely why we test APIs! Here’s what you gain
from testing APIs with Postman:
● Find problems early: Catching errors before your application goes
live saves you time, headaches, and potentially a LOT of unhappy
users.
● Keep things running smoothly: Ensure your application talks
correctly to other services it relies on. If a company updates their
weather API, you want to make sure your weather app still works!
● Build trust: Confidence that your application delivers on its
promises, boosting user loyalty and satisfaction.
What Makes Postman the Perfect Tool?
Postman is like the Swiss army knife for API testing. Here’s why it’s so
widely loved:
● Super beginner-friendly: No complex coding required to get
started. Start testing in minutes.
● Super powerful: As you learn, you’ll discover features for the most
complex testing scenarios.
● Collaboration dream: Workspaces allow teams to work together
and share knowledge easily.
● Widely used: Tons of online resources, tutorials, and help if you get
stuck.
Your Journey Ahead
This book unfolds in a carefully designed way to give you the strongest
foundation:
● The Basics: You’ll start with understanding Postman’s interface and
making your first API requests.
● API Actions: We’ll cover every essential aspect of creating,
reading, updating, and deleting data with APIs.
● Organize, Automate, and Test: Learn to streamline your work
with collections, scripts, and environments for efficiency.
● Data, Authorization & Beyond: Delve into data-driven testing,
securing your requests, and even automation using the command
line.
What You’ll Be Able to Do
By the end, you’ll transform into a true API testing pro, able to:
● Test any API out there, regardless of its complexity.
● Find hidden bugs that could break your application.
● Create detailed test reports for your team.
● Integrate API testing into your development process like a boss.
Are you ready for this adventure? If so, let’s dive into Chapter 2!
Further Resources
● Postman’s Official Getting Started Guide:
https://learning.postman.com/docs/getting-started/introduction/
● Postman Blog: https://blog.postman.com/ (Tons of helpful articles
here)
Section 1:
Introduction to Postman and API
Testing

Exploring Postman: A Primer


Welcome to the world of Postman! This powerful tool is your trusty
companion in navigating the exciting realm of API testing. Let’s start our
journey by taking a guided tour of Postman’s interface and essential
features.
Your Postman Workspace: The Mission Control Center
When you launch Postman, you’ll land in your workspace. Think of it as
your API testing headquarters. Here’s a breakdown of the key areas:
1. Sidebar: This is on the left. Here you find core functions like:

○ Workspaces: Switch between different projects or team


environments.
○ Collections: Organizes your API requests (more on this
later!).
○ APIs: A place to manage and define API specifications.
○ And more!

2. Builder: This is the central area—where the action happens.


You’ll create requests and view the responses here.
3. Request Tab: This lets you specify:

○ HTTP Method: GET (fetch data), POST (send data),


PUT/PATCH (update), DELETE, and more.
○ Request URL: The address of the API you want to ‘talk’ to.
4. Tabs (Params, Authorization, Headers, etc.): Fine-tune your
API requests with extra options for things like passing
additional data (Params) and security settings (Authorization).
5. Send Button: The magic button! Hit this to fire off your API
request.
6. Response Area: Once you hit ‘Send,’ this is where the API’s
response will appear, giving you all the details.

Important Note: Postman’s interface might evolve slightly over time. If


things look a little different, don’t worry! The core concepts stay the same.
A Quick Experiment: Your First API Request
Let’s make your first API request to get a feel for the process:
1. Choose a simple API: We’ll use a public one for practice:
https://jsonplaceholder.typicode.com/posts/1 (This API
provides sample data)
2. Set the method: In the request tab, select ‘GET’ from the
dropdown menu.
3. Enter the URL: Paste the following in the URL field:
https://jsonplaceholder.typicode.com/posts/1
4. Hit that Send button!

Boom! You’ll see a response below containing some sample data.


Congratulations, you just made your first API call using Postman!
Key Takeaways
● Postman is your user-friendly window into APIs: With Postman,
you don’t need to be a coding wizard to start testing APIs.
● The layout is designed for exploration: Even if you feel a bit
overwhelmed at first, we’ll cover everything piece by piece.
● Learning by doing is highly effective: Don’t be afraid to
experiment with different APIs and buttons within Postman.
Ready to Dive Deeper?
This was just a warm-up! Get ready to uncover Postman’s full potential as
we delve into specific features, crafting your own API requests, and testing
like a pro. Onward to Chapter 2!
Additional Resources
● Postman Quick Start Guide:
https://learning.postman.com/docs/getting-started/sending-the-first-
request/
● JSONPlaceholder (For practice APIs):
https://jsonplaceholder.typicode.com/

Unveiling Postman’s Core Features


In the previous chapter, you took your first steps with Postman. Now, let’s
go on a deeper exploration of the key features that make this tool an API
testing powerhouse.
Requests: The Heart of Postman
● HTTP Methods: Your Toolbox: GET, POST, PUT, DELETE,
PATCH, and more – each method tells the API what action you want
to perform. It’s like having a set of different verbs for precise
communication.
● URL: The API’s Address: This is where your request is going.
Think of it like a web address for the API.
● Params Tab: Add Extra Details: Attach additional information
alongside your request. Think of it like specifying options when
placing an online order.
● Authorization Tab: The Security Gatekeeper: Control how you
prove your identity to the API. We’ll delve into this in later
chapters.
● Headers Tab: More Request Fine-Tuning: Add metadata like
your browser type or the format of the data you want to receive
back.
● Body Tab: The Data Carrier: This is especially crucial for POST,
PUT and PATCH requests where you’re sending data to the server.
● Send & Receive: The ‘Send’ button initiates your adventure, and
below is where the API response appears, filled with information.
Test Scripts: Automating the Checks
Postman lets you write JavaScript code which runs after you receive the
response. This unlocks amazing possibilities:
● Simple Checks: Verify the API returned the correct status code
(e.g., “200 OK” for success).
● Advanced Verification: Dig into the response body to assert that
the data is as expected.
● Setting Variables: Capture values from the response to
dynamically use in other requests.
Pre-request Scripts: Before Things Happen
These scripts run before sending the request. Use them for:
● Setting Up Data: Populate variables or generate dynamic
information.
● Custom Logic: Build advanced workflows based on your own
needs.
Collections: Organizing Your API Adventures
Think of collections as folders for your requests. They are vital for:
● Project Structure: Group related API requests together.
● Re-Usability: Avoid repeating the same setup over and over.
● Test Suites: Collections form the backbone of your test sequences.
Environments: Adapting to Different Scenarios
Environments let you store sets of variables:
● Development, Testing, Production: Switch between different API
base URLs and settings with a click.
● Data Variations: Easily run tests with different user accounts or
configurations.
Beyond the Basics
Postman has even more to offer:
● Workspaces: Collaboration and project organization power-up.
● Monitors: Automated API health checks.
● Mock Servers: Simulate APIs for development.
Learning by Doing: A Mini-Challenge
1. Find a Public API: Try out the Reqres API https://reqres.in/.
for practice.
2. Experiment with Methods: Make GET, POST, and PUT
requests. See how the API responds.
3. Write a Simple Test: Assert that a ‘GET’ request returns a 200
status code.

Additional Resources
● Postman Learning Center: https://learning.postman.com/
● Postman Blog (Feature Announcements):
https://blog.postman.com/
Get Ready to Dive Deeper!
Now that you have a solid understanding of the core, we’re ready to build
practical API requests and master the art of API testing!
Initiating Your First API Request:
Basics Unraveled
Get ready to embark on an exciting API testing journey! In this chapter,
we’ll walk you through the step-by-step process of making your first API
request in Postman.
Step 1: Find a Beginner-Friendly API
For our practice, we’ll use a super simple API designed for testing:
● Reqres API: https://reqres.in/ (Provides user data)
Step 2: Start with a GET Request
● Create a New Request: Click the “+” button to create a new
request tab in Postman.
● Choose the HTTP Method: Select “GET” from the dropdown.
This is the most common method for retrieving data.
● Enter the URL: Paste the following in the request address bar:
[invalid URL removed]
● Explanation: This API will fetch user data. The ?page=2 part asks
for the second page of results.
Step 3: Hit the Send Button!
The moment of truth! Click the blue “Send” button. After a brief moment,
you should see a response appear below.
Step 4: Analyze the Response
Let’s break down the response:
● Status Code: This indicates success or failure. “200 OK” is the
goal!
● Response Body: Usually in JSON format, this contains the actual
data the API returned. In our case, it should be a list of users.
● Headers: Extra information about the response itself.
Step 5: Time to Experiment!
Let’s play around:
● Change the page number: Edit the URL, try a different page
value, and observe what changes in the response.
● Search the API Documentation: Find out if the Reqres API has
other endpoints (addresses) you can try.
Key Concepts (Explain in Sidebars or Callouts)
● API Endpoint: A specific “doorway” within an API. It’s part of the
URL after the main address (e.g., /users ).
● JSON: Stands for JavaScript Object Notation. It’s a common way
to structure data that APIs use, making it easy to read for both
humans and machines.
Troubleshooting Time
● Error Messages: If you get an error, Postman will show a status
code and a message. Use it as your starting point for solving the
problem. (Hint: Double-check the URL!)
● Postman Console: More advanced troubleshooting can be done in
the Postman Console (View -> Show Postman Console).
Additional Resources
● Reqres API Documentation: https://reqres.in/
● Introduction to REST APIs:
https://www.redhat.com/en/topics/api/what-is-a-rest-api
Onwards to More Complex Requests!
Congrats on your first successful API request! In the next chapter, we’ll
craft more sophisticated requests and dive deeper into the art of API testing.
Crafting Your Initial API Request: A
Step-by-Step Guide
In the previous chapter, you took your first steps with API requests. Now,
let’s get more deliberate. In this chapter, we’ll follow a structured process
for crafting different types of requests from the ground up.
Step 1: Understanding the API
Before diving into Postman, invest in these key questions:
● What does the API do? Get a high-level overview of its purpose.
● Documentation: Is there an API documentation page? It’s your
instruction manual! (Tip: Search online for “ documentation”)
● Authentication: Does it require any keys or login credentials? Get
those ready.
Step 2: Setting the Stage in Postman
1. New Request: Create a new request tab in Postman (click the
+).
2. HTTP Method: Determine the action you want to take:

○ GET: Retrieve data


○ POST: Send new data to the server
○ PUT: Replace existing data
○ PATCH: Update a portion of existing data
○ DELETE: Remove data
Step 3: Specifying the Endpoint
Enter the API endpoint (address) into the URL bar.
● Example with the Reqres API: To get a single user, your endpoint
might be https://reqres.in/api/users/1
Step 4: Adding Parameters (Optional)
● Query Parameters: Go in the ‘Params’ tab to add parameters
directly to the URL:
○ page=2 - Request page 2 of results
○ name=Michael - Search for a user named Michael
● Path Parameters: Some APIs use parameters within the URL
itself:
○ https://example.com/users/12 (Fetches details of user with
ID 12).
Step 5: Authorization (If Needed)
Head to the ‘Authorization’ tab. Here’s where you’ll select the authorization
method and provide any required credentials. We’ll cover this in detail later,
but for now, many APIs don’t need this step.
Step 6: Crafting a Body (For POST, PUT, PATCH)
If you’re sending data:
● Body tab: Select ‘raw’ and choose the format (often JSON).
● Example (Creating a new user):
{
"name": "Emily",
"job": "Software Tester"
}

Step 7: Fire Away with the Send Button!


Analyze the response and check its status code for success or failure.
Exercise Time: Practice Makes Perfect
Task 1: Explore the Reqres API
● Thoroughly read the documentation and note the different endpoints
available.
● Experiment with creating GET requests using parameters.
Task 2: Find a Different API
● Choose a simple API from this list: https://any-api.com/
● Apply the steps above to make a few sample requests against this
new API.
Pro Tip: Version Control for Your Requests
Consider using a version control system like Git for tracking changes in
your API requests. This is important for collaboration and managing
updates over time.
Additional Resources
● Guide to REST APIs: https://www.redhat.com/en/topics/api/what-
is-a-rest-api

Mastering API Requests: Practical


Implementation Tips
You now understand the fundamentals of building API requests. Let’s
sharpen your toolkit with practical strategies and often-overlooked Postman
features that will make your API testing efficient and robust.
Tip 1: The Art of Headers
The ‘Headers’ tab isn’t just for decoration. Here’s where you control vital
aspects of your request:
● Content-Type: Tell the API what data format you’re sending (often
application/json ).
● Accept: Specify the format you want the response in (also often
application/json ).
● Authentication Tokens: If the API requires authorization, your
tokens often go in a header called ‘Authorization’.
● Custom Headers: APIs might use specific headers for things like
rate limiting or special features. Read the documentation!
Tip 2: Pretty Print Your Responses
Does your JSON response look like a scrambled mess? Click the “Pretty”
button (below the response area) to format it in an easy-to-read way.
Visualizing data is crucial for debugging and understanding the API’s
output.
Tip 3: Power Up Your Parameters
● Dynamic Parameters: Use variables (e.g., {{timestamp}} ) within
the ‘Params’ tab to change values without manually editing the URL
each time. We’ll delve into variables later!
● Bulk Edit: Need to add many parameters at once? The ‘Params’ tab
has a bulk edit mode – it makes big changes easy.
Tip 4: Body Formatting Tricks
When your requests contain a body (especially for POST, PUT, PATCH),
pay attention to formatting:
● Auto-Formatting: Postman helps you write valid JSON and XML.
Use the “Pretty” button to ensure everything is structured correctly.
● Raw vs. Form Data vs. Other: The Body tab offers different
format options. Match the one the API expects.
Tip 5: Examine the Full Response
The default view is the response ‘Body’. Don’t forget these tabs:
● Cookies: APIs may set cookies that influence future requests.
● Headers: The response headers contain valuable details about the
server, rate limits, and more.
Mini-Challenge
Let’s practice these tips!
1. Find an API Requiring an API Key: Many weather or map
APIs use this for authorization.
2. Get the API Key: Follow their instructions to obtain it.
3. Request with Authorization Header: Add the ‘Authorization’
header to your request along with your API key.

Pro-Tip: Status Code Checks


Always check the response status code! Postman highlights common ones:
● Green (200s): Generally means success.
● Yellow (400s): Potential client-side error (bad data sent).
● Red (500s): Likely server-side problem.
Additional Resources
● HTTP Headers List: https://developer.mozilla.org/en-
US/docs/Web/HTTP/Headers
● HTTP Status Codes Explained: https://developer.mozilla.org/en-
US/docs/Web/HTTP/Status
Section 2:
CRUD Operations with Postman
Creating POST Requests: Dive into
Data Transmission
With GET requests, you fetched data. Now, it’s time to send data to an API
using the mighty POST request. POST is commonly used for actions like:
● Creating New Users: Sign-up forms often use POST under the
hood.
● Submitting Articles or Comments: Think of posting on a forum or
blog.
● Placing Orders: Ecommerce stores rely on POST for processing
orders.
The Anatomy of a POST Request
1. HTTP Method: Set this to ‘POST’ in Postman.
2. URL: The API endpoint specifically designed to receive new
data.
3. Headers: Usually, you’ll specify ‘Content-Type:
application/json’ to indicate you’re sending JSON data.
4. Body: This is the heart of the request, containing the data you
want to create on the server.

Let’s Build: Creating a New Blog Post (Example)


Imagine an API with the following endpoint for creating blog posts:
● URL: https://example.com/api/create_blog_post
● Required Data (JSON):
{
"title": "My Amazing Post",
"content": "This is the best blog content ever...",
"author": "Your Name"
}
Steps in Postman
1. Method & URL: Set the method to POST and paste the URL.
2. Headers: Add a header with key: Content-Type and value:
application/json .
3. Body: Go to the ‘Body’ tab, select ‘raw’, and choose ‘JSON’.
Paste your JSON data.
4. Send! If successful, expect a 201 Created status code and
potentially the created blog post details in the response.

Common Pitfalls
● Incorrect Content-Type: Double-check the API documentation for
what it expects.
● Invalid Data: The API likely has validation rules. Refer to its
documentation to ensure your data is correct.
● Authorization Issues: Some POST endpoints require
authentication.
Practice Time: API Signup
1. Find an API with a Signup Endpoint: Websites with free
trials are a good bet (make sure they have a test mode!).
2. Read the Docs: Determine the endpoint, required data format,
and authentication needs.
3. Craft your POST: Create a POST request to sign up a new test
user.

Advanced Concept: Idempotency


Ideally, sending the same POST request multiple times shouldn’t create
duplicate data. Good APIs are ‘idempotent’ in this respect. Always read the
documentation to understand how a specific POST endpoint behaves.
Additional Resources
● HTTP POST Method Explained: https://developer.mozilla.org/en-
US/docs/Web/HTTP/Methods/POST
● Designing REST APIs (Focus on POST):
https://restfulapi.net/resource-naming/
Next Up: Advanced POST Techniques
POST requests can get even more sophisticated! In the next chapter, we’ll
explore techniques for uploading files, sending complex data, and ways to
handle different POST request scenarios.

POST Requests Demystified:


Advanced Techniques
You now understand the fundamentals of POST requests. Let’s explore
some powerful techniques that will help you handle more complex API
testing scenarios.
Technique 1: File Uploads
Many APIs allow file uploads (think profile pictures or documents). Here’s
how Postman handles this:
1. Body Tab: Choose ‘form-data’ This format is specifically
designed for sending files along with other data.
2. Key-Value Pairs Add a key named something like ‘file’.
3. Switch Value Type: Click the value field next to your ‘file’ key
and change it from ‘Text’ to ‘File’. Select the file from your
computer.
4. Additional Data: Use other key-value pairs to send any
supporting text information the API requires
Technique 2: Complex Data Structures
What if you need to create deeply nested data with POST? JSON shines
here:
{
"name": "Emily",
"job": "Software Tester",
"address": {
"street": "123 Main St",
"city": "Anytown"
},
"skills": ["API Testing", "JavaScript", "Python"]
}
● Nested Objects: {address: { ... }} creates an ‘address’ object
within the main data.
● Arrays: ["API Testing", ...] creates an array to store multiple skills.
Technique 3: Dynamic Data with Variables
To avoid hardcoding values in your POST requests, use variables:
1. Create a Variable: (We’ll cover variables more later, but let’s
say you created one called randomUserName ).
2. Use in Body: Replace hardcoded usernames with
{{randomUserName}}

Now, each time you send the POST request, Postman will substitute a new
random value, which is great for testing.
Technique 4: Beyond JSON
While JSON is king, sometimes APIs accept other formats:
● XML: Postman can handle this. Choose ‘XML’ in the Body tab’s
formatting.
● form-data: Designed for mimicking web form submissions.
● x-www-form-urlencoded Another way to format forms, common
in older APIs.
Pro Tip: Read the Docs THOROUGHLY
The best way to master advanced POST techniques is to carefully study the
API’s documentation. Pay attention to:
● Acceptable Formats: What kind of data can you send in the POST
body?
● Special Headers: There might be unique headers for file uploads or
other actions.
Exercise: Advanced Signup Form
1. Find an Advanced API: Look for an API that lets you create
user accounts with a nested address structure or allows profile
picture uploads.
2. Study the Docs: Dissect the required data format and any
specific instructions.
3. Build Your POST: Employ the right techniques to craft a
powerful POST request.

Additional Resources
● Working with Files in Postman:
https://learning.postman.com/docs/sending-requests/supported-api-
frameworks/file-upload/#sending-files
● Complex JSON Structures:
https://www.w3schools.com/js/js_json_objects.asp
Next: Updates with PUT and PATCH
Now that you can create data with POST, the next step is learning how to
modify existing data with the PUT and PATCH requests!
Managing Resources: Understanding
PUT & PATCH Requests
Let’s say you’ve created a user profile with a POST request. Now, you need
to change their information. That’s where PUT and PATCH come in.
PUT: The Resource Replacer
● Usage: Completely replace an existing resource.
● Method: Set the HTTP method to ‘PUT’.
● URL: Target the specific resource’s endpoint (Example:
https://example.com/api/resource/123)
● Body: Send the FULL updated data with all fields, whether you’re
changing them or not.
Example: Fully Overwriting a Blog Post
Imagine you need to completely replace a blog post. Your PUT request
might look like this:
{
"id": 123,
"title": "My NEW Amazing Post",
"content": "Updated content goes here...",
"author": "Your Name"
}

PATCH: The Partial Updater


● Usage: Modify only specific fields of a resource.
● Method: Set the HTTP method to ‘PATCH’.
● URL: Same as PUT, targets the specific resource.
● Body: Send ONLY the fields you intend to change.
Example: Modifying a User’s Email Address
Let’s say you only want to update a user’s email:
{
"email": "newemail@example.com"
}

PUT vs. PATCH: The Key Difference


● PUT: Idempotent. Sending the same data multiple times has no
extra side-effects.
● PATCH: Not necessarily idempotent. Repeated PATCH requests
might have further effects.
When to Use Which?
● Full replacement of data: PUT is your choice.
● Only changing a few fields: PATCH is more efficient.
● Unsure or API is strict: PUT is generally safer due to
idempotence.
Pro-Tip: Error Codes Matter
● 200 OK: Usually for successful updates.
● 201 Created: May be used when PUT creates a new resource.
● 404 Not Found: The resource you’re targeting doesn’t exist.
Challenge Time
1. Use the API from previous chapters: Practice both PUT and
PATCH on it.
2. Intentionally Trigger Errors: Modify the resource ID in your
PUT/PATCH url to a non-existent one to observe error codes.
3. Read the Docs: Check how your API handles both PUT and
PATCH. Does it enforce the distinction?

Additional Resources
● HTTP PUT Method: https://developer.mozilla.org/en-
US/docs/Web/HTTP/Methods/PUT
● HTTP PATCH Method: https://developer.mozilla.org/en-
US/docs/Web/HTTP/Methods/PATCH
● REST API Design (PUT vs. PATCH): https://restfulapi.net/rest-
put-vs-patch/

Enhancing Resource Updates:


Advanced PUT & PATCH Tactics
In the previous chapter, you mastered the basics of modifying resources
with PUT and PATCH. Now, let’s explore some powerful techniques to
finesse your API updates.
Tactic 1: Conditional Updates (Avoiding Conflicts)
Imagine multiple users editing the same resource at once. We need ways to
prevent accidental overwrites and conflicts:
● ETags and If-Match: Some APIs use a header called ‘ETag’,
which is like a version stamp for a resource. You can include the ‘If-
Match’ header in your PUT/PATCH request with the Etag value.
The update will only succeed if the resource hasn’t changed on the
server.
● Optimistic Locking: This involves fetching the latest data,
modifying it locally, and then sending the update with some
identifier indicating the original version you based your changes on.
It’s up to the API to handle the conflict resolution.
Tactic 2: Partial Updates with Merge PATCH
While standard PATCH lets you update specific fields, sometimes you want
more fine-grained control within a field:
● Merge PATCH (Non-Standard): Some APIs support a “merge
PATCH” behavior. This allows you to send a JSON fragment that is
deeply merged onto the existing resource, making it possible to
modify even parts of an object or array.
● API-Specific Solutions: Be sure to check the API docs for any
custom update methods.
Example: Merge PATCH for Nested Updates
Let’s say you only want to change the billing address within a customer
profile. Normal PATCH would overwrite everything. Merge PATCH lets
you do this:
{
"address": {
"billing": {
"street": "New Billing Street"
}
}
}

Tactic 3: Handling Relationships


Often, resources have relationships to each other (e.g., order has line items).
Here’s how PUT/PATCH can work in these scenarios:
● Nested Updates: Sometimes you can update a parent and its
children in one PUT/PATCH.
● Separate Endpoints: Many APIs have dedicated endpoints for
managing relationships (add an item to an order, etc.)
Practice Time: API Case Study
1. Choose an API with Relationships: E-commerce or project
management APIs are good candidates.
2. Documentation Study: Thoroughly understand how this API
handles updates both for single resources and connected ones.
3. Practice Updates: Test scenarios like:

○ Modifying a single attribute


○ Changing a relationship (assigning a task to a user, etc.)
Additional Resources
● HTTP ETag for Optimistic Locking:
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/ETag
● JSON Merge Patch: https://tools.ietf.org/html/rfc7396
Next Up: Cleaning Up with DELETE
You’re now a PUT/PATCH power user! Next, let’s learn how to
strategically remove data with the DELETE request.

Deletion Simplified: The DELETE


Request Unveiled
The DELETE request is the final piece of the CRUD puzzle. While
seemingly simple, it’s crucial to understand its nuances for safe and
effective API testing.
The Basics of DELETE
1. Method: Set this to ‘DELETE’ in Postman.
2. URL: Targets the specific resource you intend to remove (e.g.,
https://api.example.com/resource/123).
3. Headers: Usually none are needed, but some APIs implement
authorization checks within DELETE.
4. Body: Generally empty, but some APIs may have strict
requirements.

Things to Consider
● Permissions: Are you authorized to delete the resource?
● Cascading Deletes: Does deleting the resource also remove
associated data? This behavior varies greatly between APIs.
● Success Responses:
○ 200 OK (Resource deleted)
○ 202 Accepted (Deletion may be asynchronous)
○ 204 No Content (Successful deletion, no data to return)
● Idempotent, But… Repeated DELETE requests may have different
responses (e.g., 204 the second time since the resource is gone).
DELETE in Practice
Let’s imagine you want to delete a blog post with the ID 123:
● Method: DELETE
● URL: https://example.com/blog/posts/123
● Check Authorization
Cautionary Tales
● Accidental Deletion: Double-check your URLs! Test in non-
production environments first.
● Orphan Data: APIs without cascading deletes might leave behind
fragments of related data.
Pro Tip: “Soft Delete”
Some APIs implement a “soft delete” where the resource is marked as
deleted but not actually removed from the database. This may allow for
recovery later.
Hands-On Challenge
1. Find an API with DELETE Capability: Look for endpoints
allowing deletion of test users, posts, etc.
2. Documentation!: Understand the API’s deletion behavior and
authorization.
3. Intentional Errors: Test deleting non-existent resources to
observe error codes.
4. Inspect Responses: Check the response status codes and any
returned data.

Additional Resources
● HTTP DELETE Method: https://developer.mozilla.org/en-
US/docs/Web/HTTP/Methods/DELETE
● API Design: Hard delete vs. Soft delete:
https://nordicapis.com/api-design-101-hard-delete-vs-soft-delete/
Congratulations! Mastering CRUD
You can now Create, Read, Update, and Delete data using an API. That’s a
powerful skill!
Up Next: Organizing with Collections
Let’s move on to organizing your API requests and test suites with Postman
Collections for improved workflows and streamlined testing!
Section 3:
Organizing with Collections

Harnessing the Power of Collections:


Overview and Benefits
So far, you’ve built API requests individually. Postman Collections are like
folders that supercharge your testing process.
Why Collections Matter
● Organization: Group related requests together. Imagine a
collection dedicated to “User Management” with requests for
creating users, updating profiles, deleting accounts, etc.
● Reusability: Avoid redundancy. Instead of crafting similar requests
over and over, a collection lets you save them and reuse with minor
tweaks.
● Test Workflows: Collections form the backbone of API test suites.
You can chain requests within a collection to model a sequence of
actions, like sign-up followed by profile update.
● Collaboration: Collections are easily shareable within your team or
the broader Postman community, promoting teamwork and
knowledge sharing.
Key Concepts
● Collections as Project Folders: Treat a collection like a folder for a
specific API or testing scenario.
● Requests as Files: Each API request you create lives within a
collection.
● Nested Folders (Optional): Organize complex collections with
subfolders for even better structure.
Real-World Benefits
1. Speed: Collections save you time. No more rebuilding common
API request patterns from scratch.
2. Consistency: Run the same test suites repeatedly, ensuring
consistent behavior across different environments or after API
updates.
3. Modularity: Break down large tests into smaller, logical
collections (login collection, product search collection, etc.),
promoting maintainability.
4. Automation: Collections are fundamental to automating your
API tests using tools like Newman.

Example Collections
● E-commerce API:
○ Collection: Product Management
○ Requests: Get Product, Add Product, Update Product Price,
etc.
● Weather API:
○ Collection: Forecast Retrieval
○ Requests: Get Current Weather (location parameter), Get 5-
day Forecast, etc.
Get Ready to Build
Collections don’t build themselves! Here’s a quick exercise to kick things
off:
1. Existing Requests: Look at requests you built in previous
chapters. Can you group them into logical collections?
2. API Documentation Study: Structure your collections to
mirror the functionality or major sections of the API you’re
working with.

Additional Resources
● Postman Collections Guide:
https://learning.postman.com/docs/sending-requests/intro-to-
collections/
● Organizing Your API Work with Collections:
https://learning.postman.com/docs/designing-and-developing-your-
api/the-api-workflow/organizing-your-api-work-with-collections/
Up Next: Building Your First Collection
Let’s get our hands dirty. In the next chapter, we’ll walk step-by-step
through creating and structuring your first Postman collection!

Building Your First Collection:


Structuring Your Workflows
It’s time to organize your API testing superpowers with your very own
Postman Collection. Let’s go step-by-step.
Step 1: Creating the Collection
1. The Big Plus Button: In the main workspace area, click the
“+” button.
2. Choose ‘Collection’: A pop-up will appear. Select ‘Collection’.
3. Name and Describe: Give your collection a name (example:
“Reqres User API Tests”) and an optional description to
summarize its purpose.
4. Click ‘Create’: Your collection is born!

Step 2: Populating Your Collection


There are two main ways to add requests:
Option 1: New Requests
1. Within the Collection: Click the “…” next to your collection’s
name in the sidebar.
2. Select ‘Add Request’: This opens a new request tab, ready for
you to build your API call.

Option 2: Importing Existing Requests


1. Drag and Drop: If you have requests open in tabs, you can
literally drag them into your collection in the sidebar.
2. “…” Menu: The “…” menu next to your collection also has an
“Add requests” option, letting you select existing requests.

Step 3: Structuring the Collection


● Think Like the API: Mirror the major sections of the API
documentation. If the API has user, product, and order management,
consider creating subfolders with those names within your
collection.
● Drag to Rearrange Drag and drop requests and folders within the
collection to organize in the way that makes most sense for your
tests.
Task Time: Build Using the Reqres API
We’ll use Reqres (https://reqres.in/) for practice:
1. Collection Name: “Reqres API Tests”
2. Requests:

○ GET a single user


○ GET a list of users
○ POST create a new user
Pro Tip: Authorization and Variables
As you become comfortable with collections, these features can live at the
collection level and automatically apply to all requests within it:
● Authorization: Set up authentication used by all requests in the
collection
● Variables: Define variables used across requests (think base URLs
and common parameters).
Additional Resources:
● Postman: Creating Collections:
https://learning.postman.com/docs/designing-and-developing-your-
api/the-api-workflow/creating-collections/
Next Up: Harnessing the Power of Variables
Collections streamline your API testing, but it’s variables that will truly
unlock their potential. Let’s learn to make your tests even more dynamic
with variables!
Section 4:
Harnessing Variables

Variable Mastery: From Creation to


Implementation
Tired of manually changing values in your requests each time? Variables are
here to save the day, making your API tests reusable, dynamic, and easier to
manage.
Why Variables Are Awesome
1. Reusability: Set a value once, use it in multiple requests or
across collections. Change the value in one place, and it
updates everywhere.
2. Environment Agility: Switch between test and production
environments by changing a single ‘baseURL’ variable.
3. Data-Driven Testing: Use variables to feed different input
values into your tests (e.g., test with multiple usernames).
4. Cleaner Requests: Avoid hardcoded values, making requests
easier to read.

Introducing Variable Scopes


Variables in Postman exist at different levels. Understanding this is key:
● Global: Accessible anywhere in your Postman workspace.
● Environment: Belong to a specific environment (we’ll cover
environments later).
● Local: Temporary, valid within a single request run.
● Data: Come from external files (CSV, JSON), for data-driven
testing.
Creating Variables
Let’s create a global variable named ‘baseUrl’:
1. Orange Braces: Use double curly braces to signify variables:
{{baseUrl}}
2. Global Tab: Click the eye icon next to your workspace name,
then select “Globals”.
3. Add Variable: Click “+”. Name it ‘baseUrl’. Set its initial
value to your API’s base address (e.g., https://reqres.in/api ).

Using Your Variable


● In Your Request: In the URL field, replace the hardcoded base
URL with {{baseUrl}} .
● Note: Postman will highlight variables in orange.
Practice: Create and Use Variables
1. Global vs. Local: Create another global variable
( testUsername ) and a local variable (try it in the scripts section
of a request!)
2. Modify the Reqres Collection: Set a variable for the API base
URL, if you didn’t already. Use it in your existing Reqres API
requests.

Pro-Tip: Naming Conventions


Good naming makes your variables easier to understand. A few common
patterns:
● Environment (Lowercase): dev_url , prod_url
● General Purpose (camelCase): baseUrl , apiKey
● Data-Specific (Descriptive): testUsernames
Additional Resources
● Postman Variables Documentation:
https://learning.postman.com/docs/sending-requests/variables/
● A Guide to Variables in Postman:
https://learning.postman.com/docs/sending-requests/variables/
Next Up: Advanced Variable Power
Now that you grasp the basics, let’s explore how to use variables
strategically for even more robust testing scenarios!

Leveraging Variables: Advanced


Strategies
You know how to create and use variables. Now, let’s explore some
powerful techniques that will greatly enhance your API testing workflow.
Strategy 1: Dynamic Data Generation
Let’s say you want to test user registration with multiple, unique usernames.
Postman has special variables that auto-generate values:
● randomString / randomAlphaNumeric: Random strings for
usernames or temporary data.
● $timestamp: Current timestamp, useful for unique values or
request timing.
● $guid: Globally Unique Identifier (GUID)
Example: Creating Users on the Fly
{
"name": "Test User - {{$randomString}}",
"email": "user{{$timestamp}}@example.com"
}
Strategy 2: Combining Variables
Variables can be used within other variables for flexibility:
1. Globals: Create a variable baseUrl , another called
usersEndpoint .
2. Combination: {{baseUrl}}/{{usersEndpoint}} dynamically
builds the full URL. Changing any of the parts updates the final
URL easily.

Strategy 3: Data-Driven Testing (External Files)


Use a CSV or JSON file to feed a variety of inputs into your tests:

1. CSV File:

username, password
user123, testpass
testuser, securepassword
2. Variables: Create {{username}} and {{password}} . We’ll
cover the specifics of importing files in a later chapter.

Strategy 4: Variables in Authorization


Many APIs use tokens for authorization. Set variables for:
● apiKey
● bearerToken
Use these variables within the ‘Authorization’ tab of your requests.
Task Time: Advanced Variable Workout
1. Modify Signup Test: Update your POST request for creating
users to use a combination of static values with dynamic ones
(like unique email address).
2. Experiment with $random…: Try using random variables for
non-essential fields just to observe how they work.
3. Plan for Data-Driven Tests: Think of an API endpoint in your
test suite where testing with multiple sets of different input data
would be valuable.

Pro-Tip: Variable Scope is Key


Remember! Choose the right scope for your variables. Here’s a quick recap:
● Global: Use for values that apply across your entire workspace.
● Environment: Use for things that change between environments
(dev, production, etc.).
● Local: For temporary values needed in a single request execution.
Additional Resources
● Dynamic Variables in Postman:
https://learning.postman.com/docs/designing-and-developing-your-
api/testing-your-api/dynamic-variables/
● Data-Driven Testing with Postman:
https://learning.postman.com/docs/designing-and-developing-your-
api/testing-your-api/data-driven-testing/
Next Up: Scripting for Superpowers!
Variables on their own are incredibly useful. Combine them with scripting
in Postman, and you’ll unlock a whole new level of API testing automation.

Scripting Variables: Introduction and


Setup
You’ve harnessed variables to make your requests dynamic. Now, let’s add
scripting to unleash their true potential! Postman lets you write JavaScript
to manipulate variables, control request flow, and perform advanced testing
logic.
Why Scripting Matters
● Custom Data Manipulation: Go beyond the built-in dynamic
variables. Convert data, generate custom strings, etc.
● Test Logic: Write ‘if/else’ statements to make tests react to API
responses. Pass a test only if the response code is 200, and so on.
● Workflow Control: Run requests in sequence, loop over data sets,
control execution based on conditions.
● Response Data Extraction: Extract values from API responses and
store them in variables for use in subsequent requests.
Where to Script: Pre-request and Tests
Postman offers two key areas for scripting:
1. Pre-request Scripts (Under the ‘Pre-request Script’ tab):
Code here runs before your API request is sent. Use it to set up
variables, modify headers, or perform any necessary pre-flight
tasks.
2. Tests (Under the ‘Tests’ tab): Code here executes after you
receive the API response. This is where you’ll write assertions,
extract data, and control the flow of your test suites.

Setup: Ensuring JavaScript is Ready


Let’s make sure you’re ready to script:
● Understanding JavaScript Basics: Some JavaScript knowledge is
essential. Don’t worry if you’re new, focus on variables, functions,
and simple conditional logic for now.
● Postman Sandbox: Postman has a built-in JavaScript environment,
so no external setup is needed.
Let’s Write Our First Script
Simple example (Put this in the Tests tab):
pm.test("Status code is 200", function () {
pm.response.to.have.status(200);
});

Explanation
● pm. Accesses the Postman scripting API.
● test() Creates a test with a name and a function to run.
● pm.response.to.have.status(200) Is a built-in assertion to check the
response status code.
Additional Resources
● Postman Learning Center: Scripting
https://learning.postman.com/docs/writing-scripts/intro-to-scripts/
● Postman Sandbox API Reference:
https://learning.postman.com/docs/writing-scripts/script-
references/postman-sandbox-api-reference/

Advanced Variable Scripting:


Optimization and Efficiency
You’ve embraced the power of scripting with variables. Now, let’s focus on
making your scripts as lean and performant as possible. This is especially
important as your API testing scenarios grow more complex.
Key Optimization Areas
1. Reduce Redundant Code: Look for repeated actions within
your scripts. Can you consolidate logic using functions or loops
to reduce code size?
2. Minimize API Calls: Each extra network request adds time to
your tests. Be strategic about when you extract data from API
responses, storing values efficiently in variables to avoid
unnecessary refetches.
3. Algorithm Choice: When performing calculations or complex
data transformations within your scripts, be mindful of the
JavaScript methods you use. Some built-in functions are more
efficient than others for particular tasks.
4. Scope Wisely: Choose the right variable scope (global,
environment, local) to balance reusability with minimizing
memory overhead.

Optimization Techniques
Technique 1: Script Structure
● Functions: Break down repetitive or complex logic into reusable
functions. This improves readability and makes your scripts easier
to maintain.
● Modularization: If your scripts become very long, consider
dividing them into smaller scripts that can be executed in sequence
within a collection. This promotes organization.
● Comments: Liberally use comments to explain intricate code
blocks or unconventional logic. This will be incredibly helpful when
you revisit your scripts later or if others need to understand them.
Technique 2: Efficient Variable Handling
● Setting Variables: Use pm.environment.set() or
pm.collectionVariables.set() to set environment and collection level
variables respectively. Avoid setting them repeatedly within
individual requests.
● Accessing Variables: Direct access (e.g.,
pm.environment.get("myVar") ) is generally faster than repeatedly
parsing the same JSON response to extract a value.
● Temporary Variables: When you need a variable for a very short-
term calculation, opt for a local variable to minimize overhead.
Technique 3: Asynchronous Awareness (Advanced)
● Promises: Use promises to manage asynchronous API calls within
your scripts in a structured way. Promises enhance code readability
when dealing with responses that happen “out of order”.
● Await: If you’re comfortable with modern JavaScript, the ‘await’
keyword can make handling asynchronous actions even cleaner,
letting you write code that looks more synchronous while retaining
efficient asynchronous behavior.
Example: Optimized Response Parsing
Instead of this in every single test:
var jsonData = pm.response.json();
pm.environment.set("userId", jsonData.data.id);
Do this once in a Pre-request script and then directly access the variable
when needed:
pm.environment.set("userId", pm.response.json().data.id);

Practice Time: Analyze and Improve


1. Review Scripts: Take a close look at your existing test scripts.
Identify opportunities to apply the optimization techniques
discussed.
2. Response Handling: Examine how you currently extract data
from API responses. Could you reduce the number of times
you’re parsing JSON data and streamline the storage and
retrieval of these values with variables?
3. Profiling (Advanced): Postman has a console. Experiment
with console.time() and console.timeEnd() to profile parts of
your scripts, pinpointing performance bottlenecks.

Pro Tip: The Performance Trade-off


While optimization is important, don’t let it make your code overly
complex. Prioritize code readability and maintainability alongside
performance gains. Avoid premature optimization, where you spend
excessive time on micro-improvements that may have a negligible real-
world impact.
Additional Resources
● JavaScript Optimization Basics:
https://developers.google.com/web/fundamentals/performance/rend
ering/optimize-javascript-execution
● Asynchronous Programming in JavaScript:
https://developer.mozilla.org/en-
US/docs/Web/JavaScript/Reference/Statements/async_function
Next Up: Dynamic Variables on Steroids
Let’s delve into advanced techniques for generating and manipulating
variables during test execution, pushing the boundaries of your dynamic
testing even further!

Dynamic Variable Handling:


Advanced Techniques
We’ve covered the fundamentals of variables and how scripting amplifies
them. Now, let’s unlock their full potential with techniques for generating
and manipulating variables on-the-fly during your tests.
Technique 1: Extracting Values from Responses
Another random document with
no related content on Scribd:
I hear within our house?
The ground shakes, | and the home of Gymir
Around me trembles too.”

The Serving-Maid spake:

15. “One stands without | who has leapt from his


steed,
And lets his horse loose to graze;”
. . . . . . . . . | . . . . . . . . .
. . . . . . . . . . . . . . .

Gerth spake:

16. “Bid the man come in, | and drink good mead
Here within our hall;
Though this I fear, | that there without
My brother’s slayer stands.

[113]

17. “Art thou of the elves | or the offspring of gods,


Or of the wise Wanes?
How camst thou alone | through the leaping flame
Thus to behold our home?”

Skirnir spake:

18. “I am not of the elves, | nor the offspring of


gods,
Nor of the wise Wanes;
Though I came alone | through the leaping flame
Thus to behold thy home.

19. “Eleven apples, | all of gold,


Here will I give thee, Gerth,
To buy thy troth | that Freyr shall be
Deemed to be dearest to you.”

Gerth spake:

20. “I will not take | at any man’s wish


These eleven apples ever;
Nor shall Freyr and I | one dwelling find
So long as we two live.”

Skirnir spake:

21. “Then do I bring thee | the ring that was burned


[114]
Of old with Othin’s son;
From it do eight | of like weight fall
On every ninth night.”

Gerth spake:

22. “The ring I wish not, | though burned it was


Of old with Othin’s son;
In Gymir’s home | is no lack of gold
In the wealth my father wields.”

Skirnir spake:

23. “Seest thou, maiden, | this keen, bright sword


That I hold here in my hand?
Thy head from thy neck | shall I straightway hew,
If thou wilt not do my will.”

Gerth spake:

24. “For no man’s sake | will I ever suffer


To be thus moved by might;
But gladly, methinks, | will Gymir seek
To fight if he finds thee here.”

Skirnir spake:

25. “Seest thou, maiden, | this keen, bright sword


That I hold here in my hand? [115]
Before its blade | the old giant bends,—
Thy father is doomed to die.

26. “I strike thee, maid, | with my magic staff,


To tame thee to work my will;
There shalt thou go | where never again
The sons of men shall see thee.
27. “On the eagle’s hill | shalt thou ever sit,
And gaze on the gates of Hel;
More loathsome to thee | than the light-hued
snake
To men, shall thy meat become.

28. “Fearful to see, | if thou comest forth,


Hrimnir will stand and stare,
(Men will marvel at thee;) [116]
More famed shalt thou grow | than the watchman
of the gods!
Peer forth, then, from thy prison.

29. “Rage and longing, | fetters and wrath,


Tears and torment are thine;
Where thou sittest down | my doom is on thee
Of heavy heart
And double dole.

30. “In the giants’ home | shall vile things harm


thee
Each day with evil deeds;
Grief shalt thou get | instead of gladness,
And sorrow to suffer with tears.

31. “With three-headed giants | thou shalt dwell


ever,
Or never know a husband;
(Let longing grip thee, | let wasting waste thee,—)
[117]
Be like to the thistle | that in the loft
Was cast and there was crushed.

32. “I go to the wood, | and to the wet forest,


To win a magic wand;
. . . . . . . . | . . . . . . . .
I won a magic wand.

33. “Othin grows angry, | angered is the best of the


gods,
Freyr shall be thy foe,
Most evil maid, | who the magic wrath
Of gods hast got for thyself.

34. “Give heed, frost-rulers, | hear it, giants,


Sons of Suttung,
And gods, ye too,
How I forbid | and how I ban
The meeting of men with the maid,
(The joy of men with the maid.)

[118]

35. “Hrimgrimnir is he, | the giant who shall have


thee
In the depth by the doors of Hel;
To the frost-giants’ halls | each day shalt thou fare,
Crawling and craving in vain,
(Crawling and having no hope.)

36. “Base wretches there | by the root of the tree


Will hold for thee horns of filth;
A fairer drink | shalt thou never find,
Maid, to meet thy wish,
(Maid, to meet my wish.)

37. “I write thee a charm | and three runes


therewith,
Longing and madness and lust;
But what I have writ | I may yet unwrite
If I find a need therefor.”

[119]

Gerth spake:

38. “Find welcome rather, | and with it take


The frost-cup filled with mead;
Though I did not believe | that I should so love
Ever one of the Wanes.”

Skirnir spake:

39. “My tidings all | must I truly learn


Ere homeward hence I ride:
How soon thou wilt | with the mighty son
Of Njorth a meeting make.”

Gerth spake:

40. “Barri there is, | which we both know well,


A forest fair and still;
And nine nights hence | to the son of Njorth
Will Gerth there grant delight.”

Then Skirnir rode home. Freyr stood without, and


spoke to him, and asked for tidings:

41. “Tell me, Skirnir, | ere thou take off the saddle,
Or farest forward a step:
What hast thou done | in the giants’ dwelling
To make glad thee or me?”

[120]

Skirnir spake:

42. “Barri there is, | which we both know well,


A forest fair and still;
And nine nights hence | to the son of Njorth
Will Gerth there grant delight.”

Freyr spake:
43. “Long is one night, | longer are two;
How then shall I bear three?
Often to me | has a month seemed less
Than now half a night of desire.”

[107]

[Contents]

NOTES
[108]

Prose. Freyr: concerning his father, Njorth, and the race of the
Wanes in general, cf. Voluspo, 21 and note. Snorri thus describes
Njorth’s family: “Njorth begat two children in Noatun; the son was
named Freyr, and the daughter Freyja; they were fair of aspect and
mighty. Freyr is the noblest of the gods; he rules over rain and
sunshine, and therewith the fruitfulness of the earth; it is well to call
upon him for plenty and welfare, for he rules over wealth for
mankind. Freyja is the noblest of the goddesses. When she rides to
the fight, she has one-half of the slain, and Othin has half. When she
goes on a journey, she drives her two cats, and sits in a cart. Love-
songs please her well, and it is good to call on her in love-matters.”
Hlithskjolf: Othin’s watch-tower; cf. Grimnismol, introductory prose.
He said: both manuscripts have “Then Skathi said:” (Skathi was
Njorth’s wife), but Bugge’s emendation, based on Snorri’s version, is
doubtless correct.
1. My son: both manuscripts, and many editors, have “our son,”
which, of course, goes with the introduction of Skathi in the prose. As
the stanza is clearly addressed to Skirnir, the change of pronouns
seems justified. The same confusion occurs in stanza 2, where
Skirnir in the manuscripts is made to speak of Freyr as [109]“your
son” (plural). The plural pronoun in the original involves a metrical
error, which is corrected by the emendation.

4. Elfbeam: the sun, so called because its rays were fatal to elves
and dwarfs; cf. Alvissmol, 35.

6. Gymir: a mountain-giant, husband of Aurbotha, and father of


Gerth, fairest among women. This is all Snorri tells of him in his
paraphrase of the story.

7. Snorri’s paraphrase of the poem is sufficiently close so that his


addition of another sentence to Freyr’s speech makes it probable
[110]that a stanza has dropped out between 7 and 8. This has been
tentatively reconstructed, thus: “Hither to me | shalt thou bring the
maid, / And home shalt thou lead her here, / If her father wills it |
or wills it not, / And good reward shalt thou get.” Finn Magnusen
detected the probable omission of a stanza here as early as 1821.

8. The sword: Freyr’s gift of his sword to Skirnir eventually proves


fatal, for at the last battle, when Freyr is attacked by Beli, whom he
kills bare-handed, and later when the fire-demon, Surt, slays him in
turn, he is weaponless; cf. Voluspo, 53 and note. Against the giants
grim: the condition of this line makes it seem like an error in copying,
and it is possible that it should be identical with the fourth line of the
next stanza. [111]

10. Some editors reject line 3 as spurious.

12. Line 2 is in neither manuscript, and no gap is indicated. I have


followed Grundtvig’s conjectural emendation.
13. This stanza is almost exactly like many in the first part of [112]the
Hovamol, and may well have been a separate proverb. After this
stanza the scene shifts to the interior of the house.

15. No gap indicated in either manuscript. Bugge and Niedner have


attempted emendations, while Hildebrand suggests that the last two
lines of stanza 14 are spurious, 14, 1–2, and 15 thus forming a
single stanza, which seems doubtful.

16. Brother’s slayer: perhaps the brother is Beli, slain by Freyr; the
only other references are in Voluspo, 53, and in Snorri’s paraphrase
of the Skirnismol, which merely says that Freyr’s gift of his sword to
Skirnir “was the reason why he was weaponless when he met Beli,
and he killed him bare-handed.” Skirnir himself seems never to have
killed anybody. [113]

17. Wise Wanes: cf. Voluspo, 21 and note.

18. The Arnamagnæan Codex omits this stanza.

19. Apples: the apple was the symbol of fruitfulness, and also of
eternal youth. According to Snorri, the goddess Ithun had charge of
the apples which the gods ate whenever they felt themselves
growing old. [114]

21. Ring: the ring Draupnir (“Dropper”) was made by the dwarfs for
Othin, who laid it on Baldr’s pyre when the latter’s corpse was
burned (cf. Voluspo, 32 and note, and Baldrs Draumar). Baldr,
however, sent the ring back to Othin from hell. How Freyr obtained it
is nowhere stated. Andvari’s ring (Andvaranaut) had a similar power
of creating gold; cf. Reginsmol, prose [115]after stanza 4 and note.
Lines 3 and 4 of this stanza, and the first two of stanza 22, are
missing in the Arnamagnæan Codex.

25. The first two lines are abbreviated in both manuscripts.


26. With this stanza, bribes and threats having failed, Skirnir begins
a curse which, by the power of his magic staff, is to fall on Gerth if
she refuses Freyr.

27. Eagle’s hill: the hill at the end of heaven, and consequently
overlooking hell, where the giant Hræsvelg sits “in an eagle’s guise,”
and makes the winds with his wings; cf. Vafthruthnismol, 37, also
Voluspo, 50. The second line is faulty in both manuscripts;
Hildebrand’s emendation corrects the error, but omits an effective
touch; the manuscript line may be rendered “And look and hanker for
hell.” The Arnamagnæan Codex breaks off with the fourth line of this
stanza.

28. Hrimnir: a frost-giant, mentioned elsewhere only in Hyndluljoth,


33. Line 3 is probably spurious. Watchman of the gods: Heimdall; cf.
Voluspo, 46. [116]

29. Three nouns of doubtful meaning, which I have rendered rage,


longing, and heart respectively, make the precise force of this stanza
obscure. Niedner and Sijmons mark the entire stanza as
interpolated, and Jonsson rejects line 5.

30. In Regius and in nearly all the editions the first two lines of this
stanza are followed by lines 3–5 of stanza 35. I have followed
Niedner, Sijmons, and Gering. The two words here translated vile
things are obscure; Gering renders the phrase simply “Kobolde.”

31. The confusion noted as to the preceding stanza, and a metrical


error in the third line, have led to various rearrangements and
emendations; line 3 certainly looks like an interpolation. Three-
headed giants: concerning giants with numerous heads, cf.
Vafthruthnismol, 33, and Hymiskvitha, 8. [117]

32. No gap indicated in the manuscript; Niedner makes the line here
given as 4 the first half of line 3, and fills out the stanza thus: “with
which I will tame you, / Maid, to work my will.” The whole stanza
seems to be either interpolated or out of place; it would fit better after
stanza 25.

33. Jonsson marks this stanza as interpolated. The word translated


most evil is another case of guesswork.

34. Most editors reject line 3 as spurious, and some also reject line
6. Lines 2 and 3 may have been expanded out of a single line
running approximately “Ye gods and Suttung’s sons.” Suttung:
concerning this giant cf. Hovamol, 104 and note. [118]

35. Most editors combine lines 1–2 with stanza 36 (either with the
first two lines thereof or the whole stanza), as lines 3–5 stand in the
manuscript after line 2 of stanza 30. Hrimgrimnir (“The Frost-
Shrouded”): a giant not elsewhere mentioned. Line 5, as a repetition
of line 4, is probably a later addition.

36. For the combination of this stanza with the preceding one, cf.
note on stanza 35. The scribe clearly did not consider that the stanza
began with line 1, as the first word thereof in the manuscript does not
begin with a capital letter and has no period before it. The first word
of line 3, however, is so marked. Line 5 may well be spurious.

37. Again the scribe seems to have been uncertain as to the stanza
divisions. This time the first line is preceded by a period, but begins
with a small letter. Many editors have made line 2 [119]into two half-
lines. A charm: literally, the rune Thurs (þ); the runic letters all had
magic attributes; cf. Sigrdrifumol, 6–7 and notes.

40. Barri: “The Leafy.” [120]

42. Abbreviated to initial letters in the manuscript.

43. The superscription is lacking in Regius. Snorri quotes this one


stanza in his prose paraphrase, Gylfaginning, chapter 37. The two
versions are substantially the same, except that Snorri makes the
first line read, “Long is one night, | long is the second.” [121]
[Contents]
HARBARTHSLJOTH
The Poem of Harbarth
[Contents]

Introductory Note
The Harbarthsljoth is found complete in the Codex Regius, where it
follows the Skirnismol, and from the fourth line of stanza 19 to the
end of the poem in the Arnamagnæan Codex, of which it occupies
the first page and a half.

The poem differs sharply from those which precede it in the Codex
Regius, both in metrical form and in spirit. It is, indeed, the most
nearly formless of all the Eddic poems. The normal metre is the
Malahattr (cf. Introduction, where an example is given). The name of
this verse-form means “in the manner of conversation,” and the
Harbarthsljoth’s verse fully justifies the term. The Atli poems
exemplify the conventional use of Malahattr, but in the Harbarthsljoth
the form is used with extraordinary freedom, and other metrical
forms are frequently employed. A few of the speeches of which the
poem is composed cannot be twisted into any known Old Norse
metre, and appear to be simply prose.

How far this confusion is due to interpolations and faulty


transmission of the original poem is uncertain. Finnur Jonsson has
attempted a wholesale purification of the poem, but his arbitrary
condemnation of words, lines, and entire stanzas as spurious is quite
unjustified by any positive evidence. I have accepted Mogk’s theory
that the author was “a first-rate psychologist, but a poor poet,” and
have translated the poem as it stands in the manuscripts. I have
preserved the metrical confusion of the original by keeping
throughout so far as possible to the metres found in the poem; if the
rhythm of the translation is often hard to catch, the difficulty is no
less with the original Norse.

The poem is simply a contest of abuse, such as the early Norwegian


and Icelander delighted in, the opposing figures being Thor and
Othin, the latter appearing in the disguise of the ferryman Harbarth.
Such billingsgate lent itself readily to changes, interpolations and
omissions, and it is little wonder that the poem is chaotic. It consists
mainly of boasting and of references, often luckily obscure, to
disreputable events in the life of one or the other of the disputants.
Some editors have sought to read a complex symbolism into it,
particularly by representing [122]it as a contest between the noble or
warrior class (Othin) and the peasant (Thor). But it seems a pity to
take such a vigorous piece of broad farce too seriously.

Verse-form, substance, and certain linguistic peculiarities, notably


the suffixed articles, point to a relatively late date (eleventh century)
for the poem in its present form. Probably it had its origin in the early
days, but its colloquial nature and its vulgarity made it readily
susceptible to changes.

Owing to the chaotic state of the text, and the fact that none of the
editors or commentators have succeeded in improving it much, I
have not in this case attempted to give all the important emendations
and suggestions. The stanza-divisions are largely arbitrary.

[Contents]

Thor was on his way back from a journey in the East,


and came to a sound; on the other side of the sound
was a ferryman with a boat. Thor called out:
1. “Who is the fellow yonder, | on the farther shore
of the sound?”

[123]

The ferryman spake:

2. “What kind of a peasant is yon, | that calls o’er


the bay?”

Thor spake:

3. “Ferry me over the sound; | I will feed thee


therefor in the morning;
A basket I have on my back, | and food therein,
none better;
At leisure I ate, | ere the house I left,
Of herrings and porridge, | so plenty I had.”

The ferryman spake:

4. “Of thy morning feats art thou proud, | but the


future thou knowest not wholly;
Doleful thine home-coming is: | thy mother,
methinks, is dead.”

Thor spake:

5. “Now hast thou said | what to each must seem


The mightiest grief, | that my mother is dead.”

[124]

The ferryman spake:

6. “Three good dwellings, | methinks, thou hast


not;
Barefoot thou standest, | and wearest a beggar’s
dress;
Not even hose dost thou have.”

Thor spake:

7. “Steer thou hither the boat; | the landing here


shall I show thee;
But whose the craft | that thou keepest on the
shore?”

The ferryman spake:

8. “Hildolf is he | who bade me have it,


A hero wise; | his home is at Rathsey’s sound.
He bade me no robbers to steer, | nor stealers of
steeds,
But worthy men, | and those whom well do I know.
Say now thy name, | if over the sound thou wilt
fare.”
Thor spake:

9. “My name indeed shall I tell, | though in danger I


am, [125]
And all my race; | I am Othin’s son,
Meili’s brother, | and Magni’s father,
The strong one of the gods; | with Thor now
speech canst thou get.
And now would I know | what name thou hast.”

The ferryman spake:

10. “Harbarth am I, | and seldom I hide my name.”

Thor spake:

11. “Why shouldst thou hide thy name, | if quarrel


thou hast not?”

Harbarth spake:

12. “And though I had a quarrel, | from such as


thou art
Yet none the less | my life would I guard,
Unless I be doomed to die.”

[126]

Thor spake:
13. “Great trouble, methinks, | would it be to come
to thee,
To wade the waters across, | and wet my middle;
Weakling, well shall I pay | thy mocking words,
If across the sound I come.”

Harbarth spake:

14. “Here shall I stand | and await thee here;


Thou hast found since Hrungnir died | no fiercer
man.”

Thor spake:

15. “Fain art thou to tell | how with Hrungnir I


fought,
The haughty giant, | whose head of stone was
made;
And yet I felled him, | and stretched him before
me.
What, Harbarth, didst thou the while?”

[127]

Harbarth spake:

16. “Five full winters | with Fjolvar was I,


And dwelt in the isle | that is Algrön called;
There could we fight, | and fell the slain,

You might also like