API Academy
🌐 English
  • 🌐 English
  • 🌐 繁體中文
HomePetstore APIExplore more APIs
HomePetstore APIExplore more APIs
🌐 English
  • 🌐 English
  • 🌐 繁體中文
🌐 English
  • 🌐 English
  • 🌐 繁體中文
  1. Working with APIs
  • Introduction
  • Table of Contents
  • API Academy
    • Get Started
      • What is an API?
      • How Does an API Work?
      • How to Call an API?
      • How to Read an API Documentation?
      • Chapter Summary
      • Get realtime weather
    • API Fundamentals
      • API Funtamentals: Overview
      • Method & Path
      • Parameters
      • Request Body
      • Responses
      • API Specification & OAS
      • Chapter Summary
    • Working with APIs
      • Working with APIs: Overview
      • Making Requests from Spec
      • Environments and Variables
      • Chaining Multiple Endpoints
      • Handling Authentication
      • Handling API Signatures
      • Introduction to Scripts
      • Chapter Summary
    • Mocking APIs
      • Mocking APIs: Overview
      • Smart Mock
      • Mock Expectations
      • Cloud Mock
      • Mock Scripts
      • Chapter Summary
    • Designing APIs
      • Designing APIs: Overview
      • Introduction to API Design
      • Creating Your First API Project
      • Analyzing Requirements and Planning Your API
      • Designing Data Models
      • Designing Endpoints
      • Using Components and Reusability
      • Setting Up Authentication
      • API Design Guidelines
      • Chapter Summary
    • Developing APIs
      • Developing APIs: Overview
      • Setup: Install Your AI Coding Assistant
      • Quick Start: From Spec to Running API in 30 Minutes
      • Understanding the Generated Code
      • Testing Your API with Apidog
      • Deployment: Put Your API Online
      • Chapter Summary
    • Testing APIs
      • Testing APIs: Overview
      • Getting Started: Your First Test Scenario
      • Integration Testing and Data Passing
      • Dynamic Values
      • Assertions and Validations
      • Flow Control: If, For, ForEach
      • Data-Driven Testing
      • Performance Testing
      • Test Reports and Analysis
      • CI/CD Integration
      • Scheduled Tasks and Automation
      • Advanced Testing Strategies
      • Chapter Summary
    • API Documentations
      • API Documentations: Overview
      • Publishing Your First API Doc
      • Customizing Documentation Appearance
      • Interactive Features for Consumers
      • Advanced Publishing Settings
      • Managing API Versions
      • Chapter Summary
    • Advanced API Technologies
      • API Technologies: Overview
      • GraphQL
      • gRPC
      • WebSocket
      • Socket.IO
      • Server-Sent Events (SSE)
      • SOAP
      • Chapter Summary
    • API Lifecycle
      • API Lifecycle: Overview
      • Stages of the API Lifecycle
      • API Governance
      • API Security Best Practices
      • Monitoring and Analytics
      • API Versioning Strategies
      • The Future of APIs
      • Chapter Summary
    • API Security
      • API Security: Overview
      • API Security Fundamentals
      • Authentication vs Authorization
      • Understanding OAuth 2.0 and OpenID Connect
      • JSON Web Tokens (JWT)
      • OWASP API Security Top 10
      • Encryption and HTTPS
      • Chapter Summary
    • API Tools
      • API Tools: Overview
      • The Evolution of API Tools
      • API Clients
      • Command Line Tools (cURL, HTTPie)
      • API Design and Documentation Tools
      • API Mocking Tools
      • API Testing Tools
      • All-in-One API Platforms
      • Chapter Summary
    • API Gateway
      • API Gateway: Overview
      • What is an API Gateway?
      • Key Features of API Gateways
      • API Gateway vs Load Balancer vs Service Mesh
      • Popular API Gateway Solutions
      • The BFF (Backend for Frontend) Pattern
      • Chapter Summary
  • Modern Pet Store
    • Pet
      • Get Pet
      • Update Pet
      • Delete Pet
      • Create Pet
      • List Pets
      • Upload Pet Image
    • User
      • Update User
      • Get User
      • Delete User
      • Login
      • Logout
      • Create User
    • Store
      • List Inventory
      • Create Order
      • Get Order
      • Delete Order
      • Callback Example
      • Pay for an Order
    • Payments
      • Pay Order
    • Chat
      • Create Chat Completion
    • Webhooks
      • Pet Adopted Event
      • New Pet Available Event
  • Schemas
    • Pet
    • Category
    • User
    • ApiResponse
    • OrderPayment
    • Tag
    • Order
    • Links-Order
    • PetCollection
    • Bank Card
    • Bank Account
    • Links
    • Error
HomePetstore APIExplore more APIs
HomePetstore APIExplore more APIs
🌐 English
  • 🌐 English
  • 🌐 繁體中文
🌐 English
  • 🌐 English
  • 🌐 繁體中文
  1. Working with APIs

Handling Authentication

Most real-world APIs require authentication to ensure that only authorized users can access protected resources. When you try to access a protected endpoint without proper authentication, you'll typically receive a 401 Unauthorized error.
In this article, we'll learn how to handle authentication in Apidog, using the Pet Store API as an example. We'll cover how to log in, obtain an authentication token, and use that token to access protected endpoints.

1. What Is API Authentication?#

Authentication is the process of verifying who you are. When you make an API request, the server needs to know that you're authorized to access the resource you're requesting.
The Pet Store API supports multiple authentication methods:
Bearer Token (JWT): A token-based authentication where you include a token in the request header
OAuth 2.0: A more complex authorization framework that supports different flows
For this tutorial, we'll focus on Bearer Token authentication, which is one of the most common methods.

2. The Authentication Flow#

A typical authentication flow works like this:
1.
Login: Send your credentials (username and password) to a login endpoint
2.
Receive Token: The server responds with an authentication token
3.
Use Token: Include the token in subsequent requests to access protected endpoints
In the Pet Store API:
Login endpoint: POST /user/login β€” accepts username and password, returns a token
Protected endpoints: Endpoints like POST /pets, PUT /pets/{id}, and DELETE /pets/{id} require authentication

3. Step 1: Log In and Get a Token#

Let's start by logging in to get an authentication token.

Send the Login Request#

1.
Open the "Login" endpoint (POST /user/login) in your Apidog project.
2.
Switch to the "Run" tab.
3.
In the request body, enter your credentials:
{
  "username": "johndoe",
  "password": "securePassword123"
}
4.
Click "Send" to execute the login request.
5.
After a successful login, you'll receive a response like this:
{
  "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "expiresAt": "2024-12-31T23:59:59Z"
}
The token field contains your authentication token that you'll need for subsequent requests.

Extract the Token as a Variable#

To use this token in other requests, we need to extract it and save it as a variable:
1.
In the Run tab, scroll down to the Post Processors section.
2.
Click "Add PostProcessor" and select "Extract Variable".
3.
Configure the extraction:
Variable Name: auth_token
Variable Scope: Choose "Global Variables Shared within Project"
Extraction Source: Select "Response JSON"
JSONPath Expression: Enter $.token to extract the token from the response
image.png
4.
Click "Save".
5.
Send the request again. After the request completes, the token will be stored in the {{auth_token}} variable.

4. Step 2: Use the Token in Protected Endpoints#

Now that we have the token stored in a variable, we can use it to access protected endpoints. Let's try creating a pet, which requires authentication.

Configure Bearer Token Authentication#

1.
Open the "Create a pet" endpoint (POST /pets) in your Apidog project.
2.
Switch to the "Run" tab.
3.
In the Authorization section (usually located below the URL bar), click on the Authorization tab.
4.
Select "Bearer Token" from the Type dropdown.
5.
In the Token field, enter: {{auth_token}}
image.png
Apidog will automatically format this as:
Authorization: Bearer {{auth_token}}
When you send the request, Apidog will replace {{auth_token}} with the actual token value.

Send the Authenticated Request#

1.
Fill in the request body (you can use the "Auto-generate" feature or enter values manually).
2.
Click "Send" to create the pet.
3.
If the authentication is successful, you'll receive a 201 Created response with the pet details.
If you see a 401 Unauthorized error, it means:
The token might have expired (tokens typically have an expiration time)
The token wasn't extracted correctly
The token format is incorrect
In this case, try logging in again to get a fresh token.

5. Viewing the Actual Request#

To verify that the token was included correctly, you can check the actual request:
1.
After sending the request, switch to the "Actual Request" tab in the response panel.
2.
Look at the Headers section. You should see:
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
This confirms that Apidog correctly replaced {{auth_token}} with the actual token value when sending the request.

6. Setting Authentication at Different Levels#

In Apidog, you can set authentication at different levels:

Request Level#

Set authentication for a specific endpoint (as we did above). This is useful when different endpoints require different authentication methods.

Folder/Module Level#

Set authentication for an entire folder or module. All endpoints in that folder will inherit the authentication settings. This is useful when all endpoints in a group require the same authentication.
1.
Right-click on a folder in your project tree.
2.
Select "Settings" or "Edit".
3.
Go to the Authorization tab.
4.
Configure the authentication (e.g., Bearer Token with {{auth_token}}).
5.
All endpoints in that folder will automatically use this authentication.

Global Level#

Set authentication globally for the entire project. This is useful when all endpoints require the same authentication method.

7. Other Authentication Types#

While we focused on Bearer Token authentication, Apidog supports many other authentication types:
API Key: Add a key-value pair in headers or query parameters
Basic Auth: Send username and password (Base64 encoded)
OAuth 2.0: For more complex authorization flows
Digest Auth: Challenge-response authentication
And more...
The configuration process is similar: select the authentication type in the Authorization tab and provide the necessary credentials (preferably using variables for security).

8. Key Takeaways#

Authentication verifies your identity when accessing protected API endpoints.
Bearer Token is a common authentication method where you include a token in the Authorization header.
Login flow: Send credentials β†’ Receive token β†’ Use token in subsequent requests.
Extract tokens from login responses using Post Processors and save them as variables.
Use variables (like {{auth_token}}) in the Authorization section to automatically include tokens in requests.
Set authentication at the request, folder, or global level depending on your needs.
Check actual requests to verify that authentication headers are included correctly.
Store sensitive credentials (like tokens) in variables rather than hardcoding them.

By properly handling authentication, you can securely access protected API endpoints and build complete workflows that require authorization. This is essential for working with real-world APIs that protect sensitive resources and operations.
Continue with β†’ Handling API Signatures
Modified atΒ 2025-12-25 09:39:28
Previous
Chaining Multiple Endpoints
Next
Handling API Signatures
Built with