Postman & Fetch API — Testing and Calling APIs
Why Postman & Fetch Matter
Understanding how to test and consume APIs is a core skill for any modern developer. Postman is the industry-standard tool for exploring, testing, and debugging APIs without writing a single line of code. The Fetch API, on the other hand, lets you call those same APIs directly from JavaScript in the browser or Node.js environment. Together they form a complete workflow: validate the API with Postman first, then integrate it into your application with Fetch.
Why this matters for your career:
- Postman is used by 20+ million developers worldwide — knowing it is expected in most backend and full-stack roles
- Fetch is the modern replacement for XMLHttpRequest and is built into every browser
- Many freelance projects (ERP integrations, payment gateways, CRM sync) require both Postman testing and Fetch-based frontend code
- API debugging without Postman is like debugging code without a console — unnecessarily painful
What Are Postman and Fetch?
Postman
Postman is a GUI-based API client. You enter a URL, choose an HTTP method, add headers, write a body, and click Send. Postman displays the response status, headers, and body in a clean interface. It also supports:
- Collections: group related requests together
- Environments: switch between dev/staging/production variables
- Tests: write JavaScript-based assertions to automate API testing
- Mock servers: simulate API responses before the backend is built
- Documentation: auto-generate API docs from your requests
Fetch API
The Fetch API is a native JavaScript interface for making HTTP requests. It returns Promises and uses a clean, readable syntax:
fetch('https://api.example.com/users', {
method: 'GET',
headers: {
'Authorization': 'Bearer token123',
'Content-Type': 'application/json'
}
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
This is the modern way to call APIs from frontend applications, serverless functions, or Node.js scripts.
How to Use Postman — Step by Step
1. Install and Launch
Download Postman from postman.com/downloads. Install and launch it. You can use the desktop app or the web version.
2. Create Your First Request
- Click the + tab to open a new request
- Enter a URL — try
https://jsonplaceholder.typicode.com/posts/1 - Set method to GET
- Click Send
You will see the response: status 200 OK, headers like Content-Type: application/json, and the JSON body:
{
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"body": "quia et suscipit..."
}
3. Send a POST Request
- Change method to POST
- Keep URL as
https://jsonplaceholder.typicode.com/posts - Go to the Body tab, select raw and JSON
- Enter:
{
"title": "My New Post",
"body": "This is the content of my post.",
"userId": 1
}
- Click Send
The response will include the created resource with an ID.
4. Work with Headers and Auth
Many real APIs require authentication headers. In Postman, go to the Headers tab and add:
| Key | Value |
|-----|-------|
| Authorization | Bearer your-api-key-here |
| X-API-Key | your-api-key |
| Content-Type | application/json |
Postman also has an Authorization tab that simplifies OAuth, Basic Auth, and API Key authentication.
5. Use Variables
Instead of hardcoding values, use variables:
- Define
{{base_url}}=https://jsonplaceholder.typicode.com - Define
{{post_id}}=1 - Request:
GET {{base_url}}/posts/{{post_id}}
Variables make it easy to switch between environments (dev, staging, production).
How to Call APIs with Fetch — Practical Examples
Basic GET
async function getUsers() {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/users');
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const users = await response.json();
console.log(users);
} catch (error) {
console.error('Failed to fetch users:', error);
}
}
getUsers();
POST with JSON Body
async function createPost() {
const newPost = {
title: 'Fetch API Tutorial',
body: 'Learning how to use the Fetch API for HTTP requests.',
userId: 1
};
const response = await fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(newPost)
});
const result = await response.json();
console.log('Created:', result);
}
createPost();
PUT — Update a Resource
async function updatePost(id) {
const updates = { title: 'Updated Title' };
const response = await fetch(`https://jsonplaceholder.typicode.com/posts/${id}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(updates)
});
const result = await response.json();
console.log('Updated:', result);
}
updatePost(1);
DELETE — Remove a Resource
async function deletePost(id) {
const response = await fetch(`https://jsonplaceholder.typicode.com/posts/${id}`, {
method: 'DELETE'
});
if (response.status === 200) {
console.log('Post deleted successfully');
} else {
console.log('Delete failed with status:', response.status);
}
}
deletePost(1);
Error Handling Best Practices
async function safeFetch(url, options = {}) {
try {
const response = await fetch(url, options);
if (!response.ok) {
const errorText = await response.text();
throw new Error(`${response.status}: ${errorText}`);
}
return await response.json();
} catch (error) {
console.error(`Fetch failed for ${url}:`, error.message);
throw error; // re-throw if caller needs to handle it
}
}
Postman vs Fetch: When to Use Each
| Scenario | Postman | Fetch | |----------|---------|-------| | Exploring a new API | ✅ Best choice | ❌ Overkill to write code | | Debugging a failing endpoint | ✅ Interactive, fast | ❌ Need to add console.log | | Automated testing | ✅ Has built-in test runner | ✅ Use with Jest/Vitest | | Production frontend code | ❌ Not for runtime use | ✅ The standard approach | | Quick prototyping | ✅ No code needed | ❌ Requires setup | | Serverless / backend calls | ❌ Not applicable | ✅ Node.js native |
Common Pitfalls and Solutions
| Pitfall | Solution |
|---------|----------|
| CORS errors in browser Fetch | Ensure server includes Access-Control-Allow-Origin header |
| Forgetting await with Fetch | Always await the response and the .json() call |
| Not checking response.ok | Always validate response.ok or response.status |
| Hardcoding URLs | Use environment variables or config files |
| Ignoring rate limits | Check API docs and add delays between requests |
| Sending wrong Content-Type | Always set Content-Type: application/json for JSON bodies |
Practical Workflow: Postman Then Fetch
- Prototype in Postman: Test the endpoint, verify parameters, see the response format
- Save to Collection: Organize requests for future reference
- Use Postman's "Code" feature: Click the
</>button and select JavaScript — Fetch to get ready-to-use code - Copy into your project: Paste the generated Fetch code into your frontend or backend
- Adapt and refine: Add error handling, authentication, and edge cases
This workflow saves hours of debugging and ensures your API calls work before you integrate them.
Summary
Postman and the Fetch API are complementary tools in every developer's arsenal. Postman lets you explore and debug APIs interactively without writing code, while Fetch lets you call those same APIs from your application. Mastering both gives you a complete API workflow: explore → test → code → deploy.
Key takeaways:
- Postman is the industry standard for API testing and exploration
- Fetch is the modern JavaScript API for making HTTP requests
- Always check
response.okand use try/catch with Fetch - Use Postman's code generation feature to bootstrap your Fetch calls
- Environment variables in Postman make switching between dev/production seamless
What's Next: RESTful API Design
The next chapter teaches RESTful API design principles — how to structure endpoints, name resources, use HTTP methods correctly, and design APIs that are intuitive and maintainable.