> ## Documentation Index
> Fetch the complete documentation index at: https://docs.ollie.shop/llms.txt
> Use this file to discover all available pages before exploring further.

# Request Functions

> Process HTTP requests in real-time. Handle user interactions, API calls, and webhook processing with instant responses and automatic scaling.

{/* 
Request Function Keywords: HTTP request processing, real-time responses, API endpoints, webhook handling, user interactions, Hub proxy integration, instant scaling

Core Functionality:
- Process incoming HTTP requests immediately
- Return responses directly to callers
- Handle GET, POST, PUT, DELETE, and other HTTP methods
- Support for JSON, form data, and file uploads
- Automatic request parsing and response formatting

Hub Integration Pattern:
- Trigger pattern: URL patterns that match incoming requests
- Hub proxy: https://hub.ollie.app/https://original-api.com/endpoint
- Request processing: intercept, transform, enhance original API calls
- Response enhancement: add custom business logic to API responses

Common Request Function Use Cases:
1. API Enhancement and Proxy
 - Add custom business logic to existing APIs
 - Transform data formats between services
 - Implement caching, rate limiting, authentication
 - Enhance legacy APIs with modern features

2. E-commerce and Payments
 - Custom checkout logic beyond platform capabilities
 - Payment processing with complex business rules
 - Order validation and inventory checks
 - Customer-specific pricing and discounts

3. User Authentication and Authorization
 - Custom login flows with multi-factor authentication
 - Role-based access control with complex permissions
 - JWT token generation and validation
 - Integration with external identity providers

4. Data Processing and Validation
 - Form submission handling with custom validation
 - File upload processing and transformation
 - Real-time data transformation between systems
 - Input sanitization and business rule application

Technical Implementation:
- Handler signature: export const handler = async (event: any) => Promise<any>
- Event object contains: url, method, headers, body, queryStringParameters
- Response format: { statusCode: number, headers?: object, body: string }
- Error handling: try-catch blocks with proper HTTP status codes
- Async operations: await for external API calls and database operations

HTTP Methods and Patterns:
- GET: Data retrieval and API proxy operations
- POST: Data creation, form submissions, webhook processing
- PUT/PATCH: Data updates with custom business logic
- DELETE: Resource deletion with validation and cleanup
- OPTIONS: CORS handling for browser-based requests

Hub Proxy Examples:
- E-commerce: Enhance product data with custom fields
- Analytics: Add tracking and metrics to API responses  
- Inventory: Add real-time availability to product APIs
- Pricing: Add dynamic pricing to catalog APIs
- Content: Add personalization to content APIs

Performance Considerations:
- Cold start optimization: minimal dependencies, efficient code
- Response time: typically under 100ms for simple operations
- Concurrent requests: automatic scaling based on traffic
- Memory usage: 128MB to 1GB based on function requirements
- Timeout: configurable up to 15 minutes for complex operations

Security Features:
- HTTPS by default for all requests
- Input validation and sanitization
- Rate limiting and DDoS protection
- Authentication and authorization support
- Secure environment variable handling

Common Questions:
- How do I handle different HTTP methods in my request function?
- What's the format for the event object and response?
- How do I implement the Hub proxy pattern?
- How do I handle errors and return proper HTTP status codes?
- How do I process form data and file uploads?
- What's the difference between request and response functions?

Related Concepts: response functions (post-processing), task functions (scheduled), function deployment, Hub integrations, API transformation
*/}

Request functions handle incoming HTTP requests from users. They're your main API endpoints that process user interactions, validate data, and execute business logic.

<CardGroup cols={2}>
  <Card title="When to Use" icon="lightbulb">
    * User authentication and registration
    * Form submissions and data processing
    * API endpoints and webhook handlers
    * E-commerce transactions and payments
  </Card>

  <Card title="What They Do" icon="gear">
    * Receive HTTP requests (GET, POST, PUT, DELETE)
    * Validate and process input data
    * Execute business logic
    * Return responses to users
  </Card>
</CardGroup>

## How Request Functions Work

```mermaid theme={"system"}
graph LR
    A["User makes request"] --> B["Hub routes to function"]
    B --> C["Function processes request"]
    C --> D["Return response to user"]
    
    style A fill:transparent,stroke:#666,stroke-width:1px
    style B fill:transparent,stroke:#666,stroke-width:1px
    style C fill:transparent,stroke:#666,stroke-width:1px
    style D fill:transparent,stroke:#666,stroke-width:1px
```

1. **User makes HTTP request** to your function via hub URL
2. **Hub routes** request to your function with authentication
3. **Function processes** request data and executes business logic
4. **Response returned** to user with any Hub enhancements

## Request Function Examples

<Tabs>
  <Tab title="Product Search">
    Handle product search with filters and pagination:

    **Sample URL:**

    ```text title="API Endpoint" icon="link" theme={"system"}
    https://hub.ollie.app/https://api.mystore.com/products/search?search=laptop&category=electronics&minPrice=500&maxPrice=2000&page=1
    ```

    <CodeGroup>
      ```json title="Input Data" icon="database" theme={"system"}
      {
        "queryStringParameters": {
          "search": "laptop",
          "category": "electronics", 
          "minPrice": "500",
          "maxPrice": "2000",
          "page": "1"
        }
      }
      ```

      ```typescript title="Function Implementation" icon="code" lines theme={"system"}
      export const handler = async (event) => {
        const { queryStringParameters } = event;
        const { search, category, minPrice, maxPrice, page = 1 } = queryStringParameters || {};
        
        try {
          // Build search filters
          const filters = {
            search,
            category,
            priceRange: { min: minPrice, max: maxPrice },
            page: parseInt(page),
            limit: 20
          };
          
          // Execute search operations
          const products = await searchProducts(filters);
          const total = await getProductCount(filters);
          
          return {
            statusCode: 200,
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
              products,
              pagination: {
                page: parseInt(page),
                totalPages: Math.ceil(total / 20),
                total
              }
            })
          };
        } catch (error) {
          return {
            statusCode: 500,
            body: JSON.stringify({ error: 'Search failed' })
          };
        }
      };
      ```

      ```json title="Standard Response" icon="arrow-right" theme={"system"}
      {
        "products": [
          {
            "id": "prod_123",
            "name": "MacBook Pro 14-inch"
          },
          {
            "id": "prod_456", 
            "name": "Dell XPS 13"
          }
        ]
      }
      ```
    </CodeGroup>

    <Accordion title="🚀 See Hub Enhancements">
      ```json title="Enhanced Response" icon="sparkles" theme={"system"}
      {
        "products": [
          {
            "id": "prod_123",
            "name": "MacBook Pro 14-inch",
            "price": 1899.99, // [!code ++]
            "category": "electronics", // [!code ++]
            "inStock": true, // [!code ++]
            "rating": 4.8, // [!code ++]
            "imageUrl": "https://cdn.mystore.com/prod_123.jpg", // [!code ++]
            "slug": "macbook-pro-14-inch" // [!code ++]
          },
          {
            "id": "prod_456", 
            "name": "Dell XPS 13",
            "price": 1299.99, // [!code ++]
            "category": "electronics", // [!code ++]
            "inStock": true, // [!code ++]
            "rating": 4.6, // [!code ++]
            "imageUrl": "https://cdn.mystore.com/prod_456.jpg", // [!code ++]
            "slug": "dell-xps-13" // [!code ++]
          }
        ], // [!code ++]
        "pagination": { // [!code ++]
          "page": 1, // [!code ++]
          "totalPages": 3, // [!code ++]
          "total": 47, // [!code ++]
          "hasNext": true, // [!code ++]
          "hasPrev": false // [!code ++]
        }, // [!code ++]
        "filters": { // [!code ++]
          "search": "laptop", // [!code ++]
          "category": "electronics", // [!code ++]
          "priceRange": {"min": 500, "max": 2000} // [!code ++]
        } // [!code ++]
      }
      ```

      **What Ollie Hub adds:**

      * ✅ Complete pagination with navigation info
      * ✅ Enhanced product data (images, slugs, stock status)
      * ✅ Applied filters context for better UX
      * ✅ Structured, consistent response format
    </Accordion>
  </Tab>

  <Tab title="Order Processing">
    Process customer orders with validation:

    **Sample URL:**

    ```text title="API Endpoint" icon="link" theme={"system"}
    https://hub.ollie.app/https://api.mystore.com/orders
    ```

    <CodeGroup>
      ```json title="Request Payload" icon="shopping-cart" theme={"system"}
      {
        "items": [
          {
            "productId": "prod_123",
            "quantity": 1,
            "price": 1899.99
          },
          {
            "productId": "prod_456",
            "quantity": 2,
            "price": 29.99
          }
        ],
        "payment": {
          "method": "credit_card",
          "token": "tok_1234567890",
          "amount": 1959.97
        },
        "shipping": {
          "address": "123 Main St, City, State 12345",
          "method": "standard"
        },
        "customerId": "cust_789"
      }
      ```

      ```typescript title="Order Processing Logic" icon="gear" lines theme={"system"}
      export const handler = async (event) => {
        const { body } = event;
        const orderData = JSON.parse(body);
        
        try {
          // Validate order data
          if (!orderData.items?.length) {
            return {
              statusCode: 400,
              body: JSON.stringify({ error: 'No items in order' })
            };
          }
          
          // Check inventory availability
          const availabilityCheck = await checkInventory(orderData.items);
          if (!availabilityCheck.available) {
            return {
              statusCode: 409,
              body: JSON.stringify({ 
                error: 'Items out of stock',
                unavailableItems: availabilityCheck.unavailable
              })
            };
          }
          
          // Process payment and create order
          const payment = await processPayment(orderData.payment);
          const order = await createOrder({
            ...orderData,
            paymentId: payment.id,
            status: 'confirmed'
          });
          
          return {
            statusCode: 201,
            body: JSON.stringify({
              orderId: order.id,
              total: order.total,
              estimatedDelivery: order.estimatedDelivery
            })
          };
        } catch (error) {
          return {
            statusCode: 500,
            body: JSON.stringify({ error: 'Order processing failed' })
          };
        }
      };
      ```

      ```json title="Standard Response" icon="check-circle" theme={"system"}
      {
        "success": true,
        "orderId": "ord_abc123def456"
      }
      ```
    </CodeGroup>

    <Accordion title="🚀 See Hub Enhancements">
      ```json title="Enhanced Order Response" icon="sparkles" theme={"system"}
      {
        "success": true, // [!code --]
        "orderId": "ord_abc123def456", // [!code ++]
        "total": 1959.97, // [!code ++]
        "estimatedDelivery": "2024-01-15T10:00:00Z", // [!code ++]
        "status": "confirmed", // [!code ++]
        "trackingNumber": "1Z999AA1234567890", // [!code ++]
        "paymentStatus": "completed", // [!code ++]
        "orderSummary": { // [!code ++]
          "subtotal": 1959.97, // [!code ++]
          "shipping": 0.00, // [!code ++]
          "tax": 156.80, // [!code ++]
          "total": 2116.77 // [!code ++]
        }, // [!code ++]
        "shipping": { // [!code ++]
          "method": "standard", // [!code ++]
          "carrier": "UPS", // [!code ++]
          "address": "123 Main St, City, State 12345" // [!code ++]
        }, // [!code ++]
        "items": [ // [!code ++]
          { // [!code ++]
            "productId": "prod_123", // [!code ++]
            "name": "MacBook Pro 14-inch", // [!code ++]
            "quantity": 1, // [!code ++]
            "price": 1899.99, // [!code ++]
            "status": "in_stock" // [!code ++]
          }, // [!code ++]
          { // [!code ++]
            "productId": "prod_456", // [!code ++]
            "name": "Wireless Mouse", // [!code ++]
            "quantity": 2, // [!code ++]
            "price": 29.99, // [!code ++]
            "status": "in_stock" // [!code ++]
          } // [!code ++]
        ] // [!code ++]
      }
      ```

      **What Ollie Hub adds:**

      * ✅ Real-time inventory validation
      * ✅ Secure payment processing
      * ✅ Automatic tax calculation
      * ✅ Delivery estimation with carrier info
      * ✅ Complete order summary with line items
      * ✅ Generated tracking number
    </Accordion>
  </Tab>

  <Tab title="User Authentication">
    Handle user login with JWT tokens:

    **Sample URL:**

    ```text title="Auth Endpoint" icon="link" theme={"system"}
    https://hub.ollie.app/https://auth.myapp.com/login
    ```

    <CodeGroup>
      ```json title="Login Credentials" icon="user" theme={"system"}
      {
        "email": "john@example.com",
        "password": "securePassword123"
      }
      ```

      ```typescript title="Authentication Handler" icon="shield" lines theme={"system"}
      export const handler = async (event) => {
        const { body } = event;
        const { email, password } = JSON.parse(body);
        
        try {
          // Validate user credentials
          const user = await validateUser(email, password);
          if (!user) {
            return {
              statusCode: 401,
              body: JSON.stringify({ error: 'Invalid credentials' })
            };
          }
          
          // Generate secure JWT token
          const token = await generateJWT({
            userId: user.id,
            email: user.email,
            role: user.role
          });
          
          // Update user activity
          await updateLastLogin(user.id);
          
          return {
            statusCode: 200,
            headers: {
              'Content-Type': 'application/json',
              'Set-Cookie': `token=${token}; HttpOnly; Secure; SameSite=Strict`
            },
            body: JSON.stringify({
              user: {
                id: user.id,
                email: user.email,
                name: user.name,
                role: user.role
              },
              token
            })
          };
        } catch (error) {
          return {
            statusCode: 500,
            body: JSON.stringify({ error: 'Authentication failed' })
          };
        }
      };
      ```

      ```json title="Standard Response" icon="key" theme={"system"}
      {
        "authenticated": true,
        "userId": "user_123456789"
      }
      ```
    </CodeGroup>

    <Accordion title="🚀 See Hub Enhancements">
      ```json title="Enhanced Auth Response" icon="sparkles" theme={"system"}
      {
        "authenticated": true, // [!code --]
        "userId": "user_123456789", // [!code --]
        "user": { // [!code ++]
          "id": "user_123456789", // [!code ++]
          "email": "john@example.com", // [!code ++]
          "name": "John Smith", // [!code ++]
          "role": "customer", // [!code ++]
          "permissions": ["read:profile", "write:orders"], // [!code ++]
          "lastLogin": "2024-01-12T10:30:45.123Z", // [!code ++]
          "profileComplete": true, // [!code ++]
          "preferences": { // [!code ++]
            "language": "en", // [!code ++]
            "currency": "USD", // [!code ++]
            "notifications": true // [!code ++]
          } // [!code ++]
        }, // [!code ++]
        "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...", // [!code ++]
        "expiresAt": "2024-01-13T10:30:45.123Z", // [!code ++]
        "refreshToken": "rt_abc123def456ghi789" // [!code ++]
      }
      ```

      **What Ollie Hub adds:**

      * ✅ Complete user profile with permissions
      * ✅ Secure JWT token with expiration
      * ✅ Refresh token for seamless re-authentication
      * ✅ HTTP-only cookies for security
      * ✅ User preferences and settings
      * ✅ Last login tracking
    </Accordion>
  </Tab>

  <Tab title="Webhook Handler">
    Process payment webhooks from Stripe:

    **Sample URL:**

    ```text title="Webhook Endpoint" icon="link" theme={"system"}
    https://hub.ollie.app/https://webhooks.mystore.com/stripe
    ```

    <CodeGroup>
      ```json title="Stripe Webhook Data" icon="credit-card" theme={"system"}
      {
        "id": "evt_1234567890",
        "type": "payment_intent.succeeded",
        "data": {
          "object": {
            "id": "pi_1234567890",
            "amount": 195997,
            "currency": "usd",
            "status": "succeeded",
            "metadata": {
              "orderId": "ord_abc123def456",
              "customerId": "cust_789"
            }
          }
        },
        "created": 1640995200
      }
      ```

      ```typescript title="Webhook Processor" icon="webhook" lines theme={"system"}
      export const handler = async (event) => {
        const { body, headers } = event;
        const signature = headers['stripe-signature'];
        
        try {
          // Verify webhook signature for security
          const webhookEvent = await verifyStripeWebhook(body, signature);
          
          // Handle different event types
          switch (webhookEvent.type) {
            case 'payment_intent.succeeded':
              const paymentIntent = webhookEvent.data.object;
              await updateOrderStatus(paymentIntent.metadata.orderId, 'paid');
              await sendConfirmationEmail(paymentIntent.metadata.orderId);
              break;
              
            case 'payment_intent.payment_failed':
              const failedPayment = webhookEvent.data.object;
              await updateOrderStatus(failedPayment.metadata.orderId, 'payment_failed');
              await sendPaymentFailedEmail(failedPayment.metadata.orderId);
              break;
              
            default:
              console.log(`Unhandled event type: ${webhookEvent.type}`);
          }
          
          return {
            statusCode: 200,
            body: JSON.stringify({ received: true })
          };
        } catch (error) {
          return {
            statusCode: 400,
            body: JSON.stringify({ error: 'Webhook processing failed' })
          };
        }
      };
      ```

      ```json title="Standard Response" icon="check" theme={"system"}
      {
        "received": true
      }
      ```
    </CodeGroup>

    <Accordion title="🚀 See Hub Enhancements">
      ```json title="Enhanced Webhook Response" icon="sparkles" theme={"system"}
      {
        "received": true, // [!code ++]
        "processed": true, // [!code ++]
        "eventId": "evt_1234567890", // [!code ++]
        "orderId": "ord_abc123def456", // [!code ++]
        "actions": [ // [!code ++]
          { // [!code ++]
            "type": "order_status_update", // [!code ++]
            "from": "pending", // [!code ++]
            "to": "paid", // [!code ++]
            "timestamp": "2024-01-12T10:30:45.123Z" // [!code ++]
          }, // [!code ++]
          { // [!code ++]
            "type": "email_sent", // [!code ++]
            "recipient": "john@example.com", // [!code ++]
            "template": "order_confirmation", // [!code ++]
            "timestamp": "2024-01-12T10:30:46.789Z" // [!code ++]
          }, // [!code ++]
          { // [!code ++]
            "type": "analytics_logged", // [!code ++]
            "event": "payment_succeeded", // [!code ++]
            "amount": 195997, // [!code ++]
            "timestamp": "2024-01-12T10:30:47.012Z" // [!code ++]
          } // [!code ++]
        ] // [!code ++]
      }
      ```

      **What Ollie Hub adds:**

      * ✅ Cryptographic signature verification
      * ✅ Automatic order status update (pending → paid)
      * ✅ Instant confirmation email to customer
      * ✅ Event logging for business analytics
      * ✅ Detailed processing confirmation
      * ✅ Action audit trail
    </Accordion>
  </Tab>
</Tabs>

## Best Practices

<CardGroup cols={2}>
  <Card title="Validate Early" icon="shield">
    Always validate input data first. Return helpful error messages for invalid requests.
  </Card>

  <Card title="Handle Errors Gracefully" icon="exclamation-triangle">
    Use try-catch blocks and return appropriate HTTP status codes and error messages.
  </Card>

  <Card title="Keep Functions Focused" icon="target">
    Each function should handle one specific endpoint or operation. Don't try to do everything.
  </Card>

  <Card title="Use Proper Status Codes" icon="check-circle">
    Return correct HTTP status codes: 200 for success, 400 for bad input, 404 for not found, etc.
  </Card>
</CardGroup>

## Next Steps

<CardGroup cols={3}>
  <Card title="Best Practices" icon="star" href="/ollie-hub/development/best-practices">
    Essential patterns for building robust functions
  </Card>

  <Card title="Response Functions" icon="arrow-right-arrow-left" href="/ollie-hub/core-concepts/response-functions">
    Learn to customize responses with analytics and enhancements
  </Card>

  <Card title="Task Functions" icon="clock" href="/ollie-hub/core-concepts/task-functions">
    Automate workflows with scheduled functions
  </Card>
</CardGroup>

<Info>
  **Pro Tip:** Request functions work great with Response functions to add analytics, security headers, and custom transformations automatically. Check out our [Best Practices guide](/ollie-hub/development/best-practices) for implementation patterns and security tips.
</Info>
