Part 2: Essential Foundational Knowledge
Workflow Automation Basics - Part 2: Essential Foundational Knowledge
2.1 Understanding Data Formats
JSON Basics (Must Learn)
JSON (JavaScript Object Notation) is the most commonly used data exchange format in workflows, with nearly all modern APIs using JSON.
Basic Syntax Rules
{
"name": "John Smith",
"age": 25,
"isStudent": false,
"hobbies": ["programming", "reading", "music"],
"address": {
"city": "New York",
"district": "Manhattan"
},
"phone": null
}
Data Types Explained
String
{
"message": "Hello World",
"email": "[email protected]",
"status": "success"
}
Number
{
"price": 299.99,
"quantity": 5,
"discount": 0.1
}
Boolean
{
"isActive": true,
"hasPermission": false
}
Array
{
"tags": ["workflow", "automation", "efficiency"],
"scores": [85, 92, 78, 96],
"users": [
{"name": "Alice", "role": "admin"},
{"name": "Bob", "role": "user"}
]
}
Object
{
"user": {
"profile": {
"name": "John Doe",
"avatar": "https://example.com/avatar.jpg"
},
"settings": {
"theme": "dark",
"language": "en-US"
}
}
}
Null
{
"description": null,
"optionalField": null
}
JSON Path and Data Extraction
In workflows, you often need to extract specific data from complex JSON:
{
"order": {
"id": "ORDER_001",
"customer": {
"name": "Jane Smith",
"email": "[email protected]"
},
"items": [
{
"product": "Laptop",
"price": 999,
"quantity": 1
},
{
"product": "Mouse",
"price": 29,
"quantity": 2
}
],
"total": 1057
}
}
Common extraction path examples:
- Order ID:
order.id - Customer email:
order.customer.email - First product name:
order.items[0].product - All product prices:
order.items[*].price
Common JSON Errors and Debugging
Syntax error examples:
// ❌ Error: Extra comma
{
"name": "John",
"age": 25,
}
// ❌ Error: Single quotes
{
'name': 'John',
'age': 25
}
// ❌ Error: Unquoted property names
{
name: "John",
age: 25
}
// ✅ Correct format
{
"name": "John",
"age": 25
}
Debugging tips:
- Use online JSON validators (like jsonlint.com)
- Workflow platforms usually have built-in JSON viewers
- Learn to read error messages and locate issues by line number
XML Introduction (Understanding)
While JSON is more popular, some systems (like SOAP APIs, RSS feeds) still use XML:
<?xml version="1.0" encoding="UTF-8"?>
<order>
<id>ORDER_001</id>
<customer>
<name>Jane Smith</name>
<email>[email protected]</email>
</customer>
<items>
<item>
<product>Laptop</product>
<price>999</price>
</item>
</items>
</order>
XML vs JSON comparison:
- XML is more verbose but supports attributes and namespaces
- JSON is lighter and parses faster
- Most modern APIs prefer JSON
Data Format Conversion
Workflows often need to convert between different formats:
CSV to JSON example:
Name,Age,City John,25,New York Jane,30,Los Angeles
Converts to:
[
{"Name": "John", "Age": 25, "City": "New York"},
{"Name": "Jane", "Age": 30, "City": "Los Angeles"}
]
2.2 Network Communication Basics
HTTP Protocol Core Concepts
HTTP (HyperText Transfer Protocol) is the foundation protocol for workflows to communicate with external systems.
HTTP Methods Explained
GET - Retrieve Data
- Purpose: Query, read data
- Characteristics: Idempotent, safe, cacheable
- Examples: Get user info, check order status
GET /api/users/123 Host: api.example.com Authorization: Bearer your_token_here
POST - Create Data
- Purpose: Create new resources, submit forms
- Characteristics: Not idempotent, may have side effects
- Examples: Create new user, submit order
POST /api/users
Host: api.example.com
Content-Type: application/json
Authorization: Bearer your_token_here
{
"name": "New User",
"email": "[email protected]"
}
PUT - Update Data
- Purpose: Complete resource update
- Characteristics: Idempotent
- Examples: Update user profile
PUT /api/users/123
Host: api.example.com
Content-Type: application/json
{
"name": "Updated Name",
"email": "[email protected]"
}
PATCH - Partial Update
- Purpose: Partial resource update
- Characteristics: Only update specified fields
- Examples: Update only user email
PATCH /api/users/123
Host: api.example.com
Content-Type: application/json
{
"email": "[email protected]"
}
DELETE - Delete Data
- Purpose: Delete resources
- Characteristics: Idempotent
- Examples: Delete user account
DELETE /api/users/123 Host: api.example.com Authorization: Bearer your_token_here
Understanding HTTP Status Codes
2xx Success
200 OK- Request successful201 Created- Resource created successfully204 No Content- Success but no return content
3xx Redirection
301 Moved Permanently- Permanent redirect302 Found- Temporary redirect
4xx Client Errors
400 Bad Request- Request format error401 Unauthorized- Unauthorized403 Forbidden- Access forbidden404 Not Found- Resource not found429 Too Many Requests- Too many requests
5xx Server Errors
500 Internal Server Error- Server internal error502 Bad Gateway- Gateway error503 Service Unavailable- Service unavailable
HTTP Request and Response Headers
Common request headers:
Content-Type: application/json # Request body format Authorization: Bearer abc123 # Authentication info User-Agent: WorkflowBot/1.0 # Client identifier Accept: application/json # Expected response format X-API-Key: your_api_key # API key
Common response headers:
Content-Type: application/json # Response body format X-RateLimit-Remaining: 99 # Remaining requests X-RateLimit-Reset: 1643723400 # Limit reset time Cache-Control: no-cache # Cache control
API Concepts and RESTful Design
What is an API
API (Application Programming Interface) is the interface specification between different software components. In workflows, we mainly interact with various services through Web APIs.
RESTful API Design Principles
Resource-oriented URL design:
GET /api/users # Get user list GET /api/users/123 # Get specific user POST /api/users # Create new user PUT /api/users/123 # Update user DELETE /api/users/123 # Delete user GET /api/users/123/orders # Get user's orders POST /api/users/123/orders # Create order for user
Unified response format:
{
"success": true,
"data": {
"id": 123,
"name": "John Smith",
"email": "[email protected]"
},
"message": "Operation successful",
"timestamp": "2024-01-15T10:30:00Z"
}
Error response format:
{
"success": false,
"error": {
"code": "INVALID_EMAIL",
"message": "Invalid email format",
"details": "Please provide a valid email address"
},
"timestamp": "2024-01-15T10:30:00Z"
}
Pagination and Filtering
Pagination parameters:
GET /api/users?page=1&limit=20&sort=created_at&order=desc
Filter parameters:
GET /api/orders?status=pending&created_after=2024-01-01&customer_id=123
Pagination response format:
{
"data": [...],
"pagination": {
"current_page": 1,
"per_page": 20,
"total": 150,
"total_pages": 8,
"has_next": true,
"has_prev": false
}
}
Authentication and Authorization Mechanisms
API Key Authentication
The simplest authentication method, suitable for server-to-server communication:
GET /api/data X-API-Key: your_secret_api_key_here
Advantages:
- Simple implementation
- Suitable for server-side applications
Disadvantages:
- Relatively low security
- Cannot distinguish user identity
Bearer Token Authentication
Using access tokens for authentication:
GET /api/user/profile Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
Use cases:
- Need user identity information
- Support token expiration and refresh
OAuth 2.0 Flow
OAuth is the standard authorization framework for modern web applications:
Authorization Code Flow:
- User visits authorization URL
- User grants authorization
- Receive authorization code
- Exchange authorization code for access token
- Use access token to call API
# Step 1: Redirect to authorization page https://auth.example.com/oauth/authorize? response_type=code& client_id=your_client_id& redirect_uri=https://yourapp.com/callback& scope=read write # Step 4: Exchange authorization code POST /oauth/token Content-Type: application/x-www-form-urlencoded grant_type=authorization_code& code=received_auth_code& client_id=your_client_id& client_secret=your_client_secret& redirect_uri=https://yourapp.com/callback
Signature Authentication
For high-security requirements:
# Simplified signature algorithm example
import hmac
import hashlib
import time
def generate_signature(secret_key, method, url, timestamp, body=""):
message = f"{method}\n{url}\n{timestamp}\n{body}"
signature = hmac.new(
secret_key.encode(),
message.encode(),
hashlib.sha256
).hexdigest()
return signature
Webhook Concepts
Webhooks are a type of "reverse API" that allow services to actively push data to your workflows.
Webhook vs Polling Comparison
Polling method:
Request API every minute to check for new data GET /api/orders?created_after=last_check_time
Webhook method:
When new order exists, system actively sends data to your endpoint
POST https://your-workflow.com/webhook/new-order
{
"event": "order.created",
"data": {...}
}
Advantages comparison:
- Real-time: Webhooks respond immediately, polling has delays
- Efficiency: Webhooks push on-demand, polling may waste requests
- Cost: Webhooks save API call counts
Webhook Security Verification
Signature verification example:
import hmac
import hashlib
def verify_webhook(payload, signature, secret):
expected_signature = hmac.new(
secret.encode(),
payload.encode(),
hashlib.sha256
).hexdigest()
return hmac.compare_digest(
f"sha256={expected_signature}",
signature
)
2.3 Logic Control Basics
Conditional Statements (if/else)
Basic Syntax Understanding
Conditional statements are the most important logic control structure in workflows:
if (condition) then
execute action A
else
execute action B
Types of Conditional Expressions
Simple comparisons:
age > 18 # Number comparison status == "approved" # String equality isActive == true # Boolean check
Compound conditions:
age >= 18 AND status == "verified" # AND operation role == "admin" OR role == "manager" # OR operation NOT isBlocked # NOT operation
Contains checks:
email contains "@gmail.com" # String contains tags contains "urgent" # Array contains
Existence checks:
phone is not empty # Not empty check address is null # Null check
Practical Application Examples
User permission control:
if role == "admin" or role == "manager" then
allow access to admin panel
else if role == "user" and isVerified == true then
allow access to user panel
else
deny access
Order processing logic:
if orderAmount > 1000 then
require manager approval
else if orderAmount > 500 then
require supervisor approval
else
auto approve
Email classification logic:
if subject contains "urgent" or priority == "high" then
send to urgent processing queue
else if sender contains "@partner.com" then
send to partner queue
else
send to general queue
Loop Concepts
Understanding Loop Types
For-each loop:
for each order in orders:
if order.status == "pending" then
send confirmation email to order.customer
While loop:
while hasNextPage == true:
get next page data
process current page data
update hasNextPage status
For loop:
repeat 3 times:
try to send request
if successful then exit loop
else wait 5 seconds
Data Processing in Loops
Data accumulation:
// Calculate total amount example
totalAmount = 0
for each order in orderList:
totalAmount = totalAmount + order.amount
Data filtering:
// Filter active users
activeUsers = []
for each user in userList:
if user.lastLoginTime > 30 days ago then
add user to activeUsers
Data transformation:
// Format user information
formattedUserList = []
for each user in originalUserList:
formattedUser = {
displayName: user.firstName + " " + user.lastName,
contact: user.email,
status: user.isActive ? "Active" : "Inactive"
}
add formattedUser to formattedUserList
Comparison Operators Explained
Numeric Comparisons
> greater than age > 18 >= greater than or equal score >= 60 < less than price < 100 <= less than or equal quantity <= 10 == equal to status == "active" != not equal to type != "admin"
String Comparisons
== exactly equal name == "John Smith"
!= not equal city != "New York"
contains contains email contains "@gmail.com"
starts_with starts with phone starts_with "+1"
ends_with ends with filename ends_with ".pdf"
matches regex match email matches "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$"
Array and Object Comparisons
in contained in "admin" in roles not in not contained in "blocked" not in status_list is empty is empty comments is empty is not empty is not empty tags is not empty has property has property user has property "email"
Logical Operators
Basic Logical Operations
AND (&&) and operation age > 18 AND status == "verified" OR (||) or operation role == "admin" OR role == "manager" NOT (!) not operation NOT isBlocked
Complex Logic Combinations
(age > 18 AND isVerified == true) OR role == "admin" NOT (status == "deleted" OR status == "banned") (orderAmount > 1000 AND customerType == "vip") OR (orderAmount > 5000 AND customerType == "regular")
Understanding Short-Circuit Evaluation
// AND: If first condition is false, second condition won't be checked
user != null AND user.email contains "@"
// OR: If first condition is true, second condition won't be checked
isAdmin == true OR hasPermission("write")
2.4 Data Processing Basics
String Operations
Common String Functions
// Length and search
length("Hello World") // Returns: 11
indexOf("Hello World", "World") // Returns: 6
lastIndexOf("test.txt.bak", ".") // Returns: 8
// Case conversion
toUpperCase("hello") // Returns: "HELLO"
toLowerCase("WORLD") // Returns: "world"
capitalize("john doe") // Returns: "John Doe"
// Trim and replace
trim(" hello ") // Returns: "hello"
replace("hello world", "world", "universe") // Returns: "hello universe"
replaceAll("a-b-c", "-", "_") // Returns: "a_b_c"
// Split and join
split("a,b,c", ",") // Returns: ["a", "b", "c"]
join(["a", "b", "c"], "-") // Returns: "a-b-c"
// Substring
substring("Hello World", 0, 5) // Returns: "Hello"
left("Hello World", 5) // Returns: "Hello"
right("Hello World", 5) // Returns: "World"
String Templates and Formatting
// Template strings
template = "Hello, {{name}}! You have {{count}} messages."
format(template, {name: "John", count: 5})
// Returns: "Hello, John! You have 5 messages."
// Date formatting
formatDate(now(), "YYYY-MM-DD HH:mm:ss")
// Returns: "2024-01-15 14:30:25"
// Number formatting
formatNumber(1234.567, "#,##0.00")
// Returns: "1,234.57"
Array Operations
Basic Array Methods
// Add and remove append([1, 2, 3], 4) // Returns: [1, 2, 3, 4] prepend([2, 3, 4], 1) // Returns: [1, 2, 3, 4] remove([1, 2, 3, 2], 2) // Returns: [1, 3] (removes first 2) removeAll([1, 2, 3, 2], 2) // Returns: [1, 3] (removes all 2s) // Find and check indexOf([1, 2, 3], 2) // Returns: 1 contains([1, 2, 3], 2) // Returns: true length([1, 2, 3]) // Returns: 3 isEmpty([]) // Returns: true // Slice and concatenate slice([1, 2, 3, 4, 5], 1, 3) // Returns: [2, 3] concat([1, 2], [3, 4]) // Returns: [1, 2, 3, 4]
Advanced Array Operations
// Filter filter(users, user => user.age > 18) // Returns all users older than 18 // Map transformation map(users, user => user.name) // Returns array of all user names // Find find(users, user => user.email == "[email protected]") // Returns first matching user // Sort sort(numbers, "asc") // Sort ascending sort(users, "name", "desc") // Sort by name descending // Remove duplicates unique([1, 2, 2, 3, 3, 3]) // Returns: [1, 2, 3] // Group by groupBy(orders, "status") // Group orders by status
Date and Time Processing
Date Creation and Formatting
// Current time
now() // Current timestamp
today() // Today at 00:00:00
// Date parsing
parseDate("2024-01-15")
parseDate("2024-01-15 14:30:00", "YYYY-MM-DD HH:mm:ss")
// Format output
formatDate(date, "YYYY-MM-DD") // "2024-01-15"
formatDate(date, "MM/DD/YYYY") // "01/15/2024"
formatDate(date, "YYYY年MM月DD日") // "2024年01月15日"
formatDate(date, "dddd, MMMM Do, YYYY") // "Monday, January 15th, 2024"
Date Calculations
// Addition and subtraction addDays(date, 7) // Add 7 days addMonths(date, 2) // Add 2 months addYears(date, 1) // Add 1 year subtractHours(date, 3) // Subtract 3 hours // Time difference calculations diffDays(date1, date2) // Difference in days diffHours(date1, date2) // Difference in hours diffMinutes(date1, date2) // Difference in minutes // Special dates startOfDay(date) // Start of day endOfDay(date) // End of day startOfWeek(date) // Start of week startOfMonth(date) // Start of month
Timezone Handling
// Timezone conversion toTimezone(date, "Asia/Shanghai") toTimezone(date, "America/New_York") toTimezone(date, "Europe/London") // UTC time toUTC(date) // Convert to UTC fromUTC(utcDate) // Convert from UTC to local
Data Validation
Basic Validation Functions
// Type validation
isString(value) // Is string
isNumber(value) // Is number
isBoolean(value) // Is boolean
isArray(value) // Is array
isObject(value) // Is object
isNull(value) // Is null
isEmpty(value) // Is empty
// Format validation
isEmail("[email protected]") // Email format validation
isPhone("+1 555 123 4567") // Phone format validation
isURL("https://example.com") // URL format validation
isIP("192.168.1.1") // IP address validation
Custom Validation Rules
// Length validation lengthBetween(value, 6, 20) // Length between 6-20 minLength(value, 8) // Minimum length 8 maxLength(value, 100) // Maximum length 100 // Number range validation between(value, 1, 100) // Value between 1-100 min(value, 0) // Minimum value 0 max(value, 999) // Maximum value 999 // Regular expression validation matches(value, "^[A-Za-z0-9]+$") // Only letters and numbers allowed
Error Handling Strategies
Exception Catching and Handling
try {
// Execute potentially failing operations
result = callAPI(url, data)
} catch (error) {
// Handle errors
logError("API call failed", error)
// Set default value or execute fallback
result = getDefaultValue()
} finally {
// Always executes regardless of success or failure
cleanupResources()
}
Common Error Type Handling
// Network errors
if (error.type == "NETWORK_ERROR") {
// Retry mechanism
retryCount = retryCount + 1
if (retryCount < maxRetries) {
waitSeconds(retryDelay)
continue // Re-execute
}
}
// Authentication errors
if (error.code == 401) {
// Refresh token or re-login
refreshAuthToken()
continue
}
// Rate limiting errors
if (error.code == 429) {
// Wait and retry
waitSeconds(60)
continue
}
2.5 Debugging and Testing Techniques
Logging Best Practices
Log Level Usage
// DEBUG: Detailed debugging information
debug("Processing user ID: " + userId + ", start time: " + startTime)
// INFO: General information logging
info("Successfully processed order: " + orderId + ", amount: " + amount)
// WARN: Warning information
warn("Insufficient user balance: " + userId + ", current balance: " + balance)
// ERROR: Error information
error("API call failed: " + url + ", error: " + errorMessage)
Structured Logging
log({
level: "INFO",
message: "Order processing completed",
data: {
orderId: order.id,
customerId: order.customerId,
amount: order.total,
processingTime: endTime - startTime
},
timestamp: now(),
correlationId: requestId
})
Setting Data Checkpoints
Key Node Data Validation
// Input data validation
if (isEmpty(userEmail)) {
error("User email cannot be empty")
stopExecution()
}
// Intermediate processing validation
processedData = transformUserData(rawData)
if (processedData.length != rawData.length) {
warn("Some records were lost during data transformation")
log("Original records: " + rawData.length + ", processed records: " + processedData.length)
}
// Output result validation
if (apiResponse.success != true) {
error("API call failed: " + apiResponse.message)
// Log detailed error information for debugging
debug("Full response: " + JSON.stringify(apiResponse))
}
Data Snapshot Saving
// Save data state at key steps
saveDataSnapshot("step1_raw_data", rawData)
saveDataSnapshot("step2_cleaned_data", cleanedData)
saveDataSnapshot("step3_enriched_data", enrichedData)
// Compare data states when errors occur
if (hasError) {
compareSnapshots("step2_cleaned_data", "step3_enriched_data")
}
Unit Testing Mindset
Boundary Condition Testing
// Test null cases
testCases = [
{input: null, expected: "error"},
{input: "", expected: "error"},
{input: [], expected: "empty_array"},
{input: {}, expected: "empty_object"}
]
// Test extreme values
testCases = [
{input: 0, expected: "zero"},
{input: -1, expected: "negative"},
{input: 999999999, expected: "large_number"}
]
// Test special formats
testCases = [
{input: "[email protected]", expected: "valid_email"},
{input: "invalid-email", expected: "error"},
{input: "+1 555 123 4567", expected: "valid_phone"}
]
Mock Data Creation
// Create test user data
createTestUser = function() {
return {
id: generateRandomId(),
name: "TestUser_" + timestamp(),
email: "test_" + timestamp() + "@example.com",
createdAt: now(),
isActive: true
}
}
// Create test order data
createTestOrder = function(userId) {
return {
id: generateRandomId(),
userId: userId,
items: [
{product: "Test Product", quantity: 1, price: 99.99}
],
total: 99.99,
status: "pending"
}
}
Performance Monitoring Basics
Execution Time Measurement
// Single operation timing
startTime = now()
result = expensiveOperation()
endTime = now()
executionTime = endTime - startTime
if (executionTime > 5000) { // Over 5 seconds
warn("Operation took too long: " + executionTime + "ms")
}
// Batch operation performance monitoring
batchSize = data.length
startTime = now()
processedCount = 0
for (item in data) {
processItem(item)
processedCount = processedCount + 1
// Check every 100 processed records
if (processedCount % 100 == 0) {
currentTime = now()
avgTimePerItem = (currentTime - startTime) / processedCount
estimatedTotalTime = avgTimePerItem * batchSize
info("Processed: " + processedCount + "/" + batchSize +
", estimated total time: " + estimatedTotalTime + "ms")
}
}
Resource Usage Monitoring
// API call count statistics
apiCallCount = 0
function callAPI(url, data) {
apiCallCount = apiCallCount + 1
if (apiCallCount > dailyLimit * 0.8) {
warn("API call count approaching limit: " + apiCallCount + "/" + dailyLimit)
}
return httpRequest(url, data)
}
// Memory usage monitoring (conceptual)
function processLargeDataset(data) {
if (data.length > 10000) {
info("Processing large dataset: " + data.length + " records")
// Process in batches to avoid memory overflow
return processBatches(data, 1000)
} else {
return processAll(data)
}
}
2.6 Security Awareness Basics
Sensitive Information Handling
Key and Credential Management
// ❌ Wrong: Hardcoded keys in code
apiKey = "sk_live_abcd1234567890"
// ✅ Correct: Use environment variables or configuration
apiKey = getEnvironmentVariable("API_KEY")
if (isEmpty(apiKey)) {
error("API key not configured")
stopExecution()
}
Filtering Sensitive Information in Logs
// ❌ Wrong: Log complete user data
log("Processing user data: " + JSON.stringify(userData))
// ✅ Correct: Filter sensitive fields
function logUserData(userData) {
safeData = {
id: userData.id,
name: userData.name,
email: maskEmail(userData.email), // [email protected] -> t***@example.com
// Don't log passwords, SSNs, etc.
}
log("Processing user data: " + JSON.stringify(safeData))
}
Data Transmission Security
// Ensure HTTPS usage
if (!url.startsWith("https://")) {
warn("Recommend using HTTPS protocol: " + url)
}
// Validate SSL certificates
httpOptions = {
url: url,
method: "POST",
data: data,
headers: headers,
validateSSL: true, // Validate SSL certificates
timeout: 30000 // Set timeout
}
Input Validation and Protection
Data Sanitization
// Clean user input
function sanitizeInput(input) {
if (isString(input)) {
// Remove potentially malicious characters
cleaned = input
.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, "")
.replace(/[<>\"'&]/g, "")
.trim()
return cleaned
}
return input
}
// Length limits
function validateInputLength(input, maxLength) {
if (length(input) > maxLength) {
error("Input length exceeds limit: " + length(input) + "/" + maxLength)
return false
}
return true
}
SQL Injection Prevention (if involving database queries)
// ❌ Wrong: Direct SQL concatenation query = "SELECT * FROM users WHERE email = '" + userEmail + "'" // ✅ Correct: Use parameterized queries query = "SELECT * FROM users WHERE email = ?" parameters = [userEmail]
Error Information Security
Secure Error Responses
// ❌ Wrong: Expose internal system information
if (databaseError) {
return "Database connection failed: Connection to 192.168.1.100:3306 refused"
}
// ✅ Correct: Return generic error information
if (databaseError) {
// Log detailed error internally
error("Database connection failed: " + detailedError)
// Return generic information externally
return "System temporarily unavailable, please try again later"
}
Prevent Information Leakage
function handleUserLogin(email, password) {
user = findUserByEmail(email)
if (!user) {
// ❌ Wrong: Expose whether user exists
return "User does not exist"
}
if (!verifyPassword(password, user.hashedPassword)) {
// ❌ Wrong: Expose password error
return "Password incorrect"
}
// ✅ Correct: Unified error message
if (!user || !verifyPassword(password, user.hashedPassword)) {
return "Email or password incorrect"
}
return "Login successful"
}
2.7 Practical Exercise Suggestions
Basic Skills Practice
JSON Operation Practice
// Practice data
{
"company": "Tech Company",
"employees": [
{
"id": 1,
"name": "John Smith",
"department": "Development",
"skills": ["JavaScript", "Python", "SQL"],
"salary": 8000,
"joinDate": "2023-01-15"
},
{
"id": 2,
"name": "Jane Doe",
"department": "Design",
"skills": ["Photoshop", "Figma"],
"salary": 7000,
"joinDate": "2023-03-20"
}
]
}
Practice tasks:
- Extract all employee names
- Calculate average salary
- Find employees who know Python
- Group employees by department
- Calculate each employee's years of service
API Call Practice
Mock API design:
GET /api/weather?city=NewYork POST /api/users PUT /api/users/123 DELETE /api/users/123
Practice tasks:
- Design requests for different HTTP methods
- Handle different status code responses
- Implement retry mechanisms
- Add authentication headers
- Handle paginated data
Logic Control Practice
Business scenario: E-commerce order processing
// Order data structure
order = {
id: "ORDER_001",
customerId: 123,
items: [...],
total: 299.99,
paymentMethod: "credit_card",
shippingAddress: {...},
status: "pending"
}
Practice tasks:
- Determine discount strategy based on order amount
- Choose shipping method based on product type
- Give different discounts based on user level
- Implement inventory check logic
- Design order status flow rules
Comprehensive Project Practice
Project 1: User Registration Process Automation
Requirements:
- Validate user input email format
- Check if email is already registered
- Send verification email
- Activate account after user clicks verification link
- Send welcome email
Skills involved:
- Data validation
- API calls
- Conditional logic
- Email sending
- Error handling
Project 2: Customer Service Ticket Auto-Assignment
Requirements:
- Receive new ticket data
- Automatically categorize by issue type
- Assign to appropriate customer service staff
- Send notifications to staff and users
- Track processing progress
Skills involved:
- JSON data processing
- Conditional branching logic
- Array operations
- Notification system integration
- State management
Project 3: Data Synchronization System
Requirements:
- Regularly fetch customer data from CRM system
- Clean and validate data
- Transform to target format
- Synchronize to marketing system
- Log synchronization results and exceptions
Skills involved:
- Scheduled tasks
- Data transformation
- Batch processing
- Error handling
- Logging
Learning Resource Recommendations
Online Tools
- JSON Validators: jsonlint.com, jsonformatter.org
- API Testing Tools: Postman, Insomnia, curl command
- Regular Expression Testing: regex101.com, regexr.com
- Timestamp Conversion: timestampconvert.com
Practice Platforms
- JSONPath Practice: jsonpath.com
- HTTP Status Code Reference: httpstatuses.com
- API Examples: JSONPlaceholder, httpbin.org
- Webhook Testing: webhook.site, requestcatcher.com
Documentation Resources
- HTTP Protocol: MDN Web Docs - HTTP
- JSON Standard: json.org, RFC 7159
- RESTful API Design: REST API Tutorial
- OAuth 2.0: oauth.net
Part 3 will provide detailed explanations of workflow core concepts, including triggers, nodes, connections, and other fundamental components.