Practice Endpoints: Sample REST, GraphQL, SOAP, Webhook, and WebSocket endpoints are available for student practice. Use them responsibly and avoid sending sensitive data.

API Documentation

Complete guide to APIs, integration patterns, and AdTech Update endpoints

πŸ“š What you'll learn:

From API basics to advanced integration β†’ Learn by doing with real code examples β†’ Test endpoints live in your browser β†’ Understand authentication, error handling, and best practices

Browse Sections

What is an API?

An Application Programming Interface (API) is a set of defined rules and protocols that enable different software applications to communicate with each other. Think of it as a waiter in a restaurant who takes your order (request) to the kitchen (server) and brings back your food (response).

Key Concepts

πŸ”— Endpoint

A specific URL where an API can be accessed by a client application

πŸ“€ Request

Data sent from client to server (includes method, headers, body)

πŸ“₯ Response

Data returned from server to client (includes status code, headers, body)

πŸ” Authentication

Method to verify identity (API keys, OAuth, JWT tokens)

HTTP Methods

Method Purpose Example
GET Retrieve data from server Get list of blog posts
POST Send data to server to create resource Create new user account
PUT Update existing resource Update user profile
DELETE Delete resource from server Remove blog post

Types of APIs

🌐 REST API (Representational State Transfer)

Most common API architecture using HTTP methods and stateless communication.

GET https://api.example.com/users/123 Accept: application/json Response: { "id": 123, "name": "John Doe", "email": "john@example.com" }

Best for: Web services, mobile apps, microservices

πŸ”„ GraphQL API

Query language for APIs that lets clients request exactly what they need.

POST https://api.example.com/graphql Content-Type: application/json { "query": "{ user(id: 123) { name email posts { title } } }" } Response: { "data": { "user": { "name": "John Doe", "email": "john@example.com", "posts": [ { "title": "First Post" } ] } } }

Best for: Complex data requirements, reducing over-fetching

🧼 SOAP API (Simple Object Access Protocol)

Protocol-based API using XML for message format.

POST https://api.example.com/soap Content-Type: text/xml <?xml version="1.0"?> <soap:Envelope> <soap:Body> <GetUser> <UserId>123</UserId> </GetUser> </soap:Body> </soap:Envelope>

Best for: Enterprise applications, financial services, legacy systems

⚑ WebSocket API

Real-time, bidirectional communication between client and server.

// Client const socket = new WebSocket('wss://api.example.com/live'); socket.onmessage = (event) => { console.log('Message:', event.data); }; socket.send('Hello Server!');

Best for: Chat applications, live updates, real-time dashboards

πŸ”Œ Webhook API

Event-driven API that sends data to your URL when specific events occur.

// Server sends POST request to your endpoint POST https://your-app.com/webhook Content-Type: application/json { "event": "order.created", "data": { "order_id": 456, "amount": 99.99 } }

Best for: Event notifications, payment processing, automated workflows

Getting Started with APIs

Step-by-step guide to making your first API call and understanding the fundamentals.

πŸ“š Step 1: Understanding API Requests

Every API request consists of four main components:

1. URL/Endpoint

The address where the API lives:

https://api.example.com/v1/users ↑ ↑ ↑ ↑ Protocol Domain Version Resource

2. HTTP Method

Tells the server what action to perform:

  • GET - Retrieve data (like reading a book)
  • POST - Create new data (like writing a new book)
  • PUT - Update entire resource (like rewriting a book)
  • PATCH - Update part of resource (like editing a chapter)
  • DELETE - Remove data (like throwing away a book)

3. Headers

Metadata about the request:

Content-Type: application/json // Format of data being sent Accept: application/json // Format of data you want back Authorization: Bearer YOUR_TOKEN // Your credentials User-Agent: MyApp/1.0 // Who is making the request

4. Body (for POST/PUT/PATCH)

The actual data you're sending:

{ "name": "John Doe", "email": "john@example.com", "age": 30 }

πŸš€ Step 2: Making Your First API Call

Let's make a real API call using different methods:

Method 1: Using Your Browser (Easiest)

Simply paste this URL in your browser address bar:

https://jsonplaceholder.typicode.com/users/1

You'll see JSON data about a user. This is a GET request!

Method 2: Using cURL (Command Line)

# Simple GET request curl https://jsonplaceholder.typicode.com/users/1 # GET request with headers curl -H "Accept: application/json" \ https://jsonplaceholder.typicode.com/users/1 # POST request with data curl -X POST https://jsonplaceholder.typicode.com/posts \ -H "Content-Type: application/json" \ -d '{"title":"My Post","body":"This is my post","userId":1}' # Pretty print JSON response curl https://jsonplaceholder.typicode.com/users/1 | python -m json.tool

Method 3: Using Browser Console (Interactive)

Press F12 in your browser, go to Console tab, and paste:

// Simple GET request fetch('https://jsonplaceholder.typicode.com/users/1') .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error('Error:', error)); // POST request fetch('https://jsonplaceholder.typicode.com/posts', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ title: 'My First Post', body: 'This is amazing!', userId: 1 }) }) .then(response => response.json()) .then(data => console.log('Success:', data)) .catch(error => console.error('Error:', error));

πŸ” Step 3: Understanding API Responses

HTTP Status Codes (What they mean):

Code Meaning What to Do
200 OK - Success! Everything worked perfectly
201 Created Your resource was successfully created
400 Bad Request Check your data format/parameters
401 Unauthorized Check your API key/credentials
403 Forbidden You don't have permission
404 Not Found Check your URL/endpoint
429 Too Many Requests Slow down, you hit rate limit
500 Server Error Problem on server side, try again later

Response Example with Explanation:

// Status Code: 200 (Success!) // Headers: Content-Type: application/json X-RateLimit-Remaining: 99 Date: Tue, 12 Nov 2025 10:30:00 GMT // Body: { "status": "success", // Custom status from API "data": { // Your actual data "id": 123, "name": "John Doe", "email": "john@example.com" }, "meta": { // Additional metadata "timestamp": "2025-11-12T10:30:00Z", "version": "1.0" } }

πŸ› οΈ Step 4: Practical Exercise

Try these exercises with a free public API:

Exercise 1: Get List of Users

fetch('https://jsonplaceholder.typicode.com/users') .then(res => res.json()) .then(users => { console.log(`Total users: ${users.length}`); users.forEach(user => console.log(`${user.id}. ${user.name}`)); });

Exercise 2: Create a New Post

fetch('https://jsonplaceholder.typicode.com/posts', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ title: 'Learning APIs', body: 'APIs are awesome!', userId: 1 }) }) .then(res => res.json()) .then(post => console.log('Created post with ID:', post.id));

Exercise 3: Update and Delete

// Update a post fetch('https://jsonplaceholder.typicode.com/posts/1', { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ id: 1, title: 'Updated Title', body: 'Updated content', userId: 1 }) }) .then(res => res.json()) .then(data => console.log('Updated:', data)); // Delete a post fetch('https://jsonplaceholder.typicode.com/posts/1', { method: 'DELETE' }) .then(res => { if (res.ok) console.log('Deleted successfully!'); });

⚠️ Common Mistakes to Avoid

❌ Forgetting Content-Type Header

Wrong:

fetch(url, {method: 'POST', body: JSON.stringify(data)})

Right:

headers: {'Content-Type': 'application/json'}

❌ Not Handling Errors

Always include error handling:

fetch(url) .then(res => { if (!res.ok) throw new Error(`HTTP error! status: ${res.status}`); return res.json(); }) .catch(error => console.error('Something went wrong:', error));

❌ Exposing API Keys in Frontend Code

Never put secret API keys in JavaScript! Use environment variables or backend proxy.

❌ Not Checking Rate Limits

Many APIs limit requests. Check headers like X-RateLimit-Remaining.

🎯 Quick Tips for Success

  • πŸ“–
    Read the Documentation: Always start with the API docs to understand endpoints, parameters, and authentication.
  • πŸ”‘
    Test in Postman: Use tools like Postman or Insomnia to test API calls before writing code.
  • πŸ›
    Use Browser DevTools: Network tab shows you exactly what's being sent and received.
  • πŸ’Ύ
    Cache When Possible: Don't request the same data repeatedly. Store it locally when appropriate.
  • πŸ”’
    Always Use HTTPS: Never send sensitive data over HTTP (non-encrypted).

πŸ” API Authentication Methods

Authentication verifies who you are and gives you access to protected resources. Think of it like showing your ID at a security checkpoint.

Expand / Collapse Authentication Details

πŸ”‘ 1. API Keys (Simplest)

A unique string that identifies your application. Like a password, but for apps.

How it works:

  1. Sign up for API service β†’ Get your API key
  2. Include key in every request (header or query param)
  3. Server validates key β†’ Grants/denies access

Example 1: API Key in Header

// JavaScript example fetch('https://api.example.com/data', { headers: { 'X-API-Key': 'your_api_key_here_abc123xyz', 'Content-Type': 'application/json' } }) .then(res => res.json()) .then(data => console.log(data)); // cURL example curl -H "X-API-Key: your_api_key_here_abc123xyz" \ https://api.example.com/data

Example 2: API Key in Query Parameter

// JavaScript fetch('https://api.example.com/data?api_key=your_api_key_here_abc123xyz') .then(res => res.json()) .then(data => console.log(data)); // Simple URL (paste in browser) https://api.example.com/data?api_key=your_api_key_here_abc123xyz

⚠️ Security Note: Never share API keys publicly! Don't commit them to GitHub. Use environment variables instead.

🎫 2. Bearer Tokens (JWT)

A token you receive after login that proves your identity. Like a temporary backstage pass.

Step 1: Login to Get Token

// Login request fetch('https://api.example.com/auth/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email: 'user@example.com', password: 'your_password' }) }) .then(res => res.json()) .then(data => { const token = data.access_token; localStorage.setItem('token', token); // Save for later console.log('Token received:', token); });

Step 2: Use Token in Requests

// Get token from storage const token = localStorage.getItem('token'); // Make authenticated request fetch('https://api.example.com/user/profile', { headers: { 'Authorization': `Bearer ${token}`, 'Content-Type': 'application/json' } }) .then(res => res.json()) .then(profile => console.log(profile));

βœ… JWT Token Structure:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c ↑ Header ↑ Payload (your data) ↑ Signature

Three parts separated by dots: Header.Payload.Signature

πŸ”’ 3. OAuth 2.0 (Most Secure)

Allows apps to access your data without knowing your password. Used by Google, Facebook, Twitter for "Login with..." features.

OAuth Flow (Simplified):

  1. User clicks "Login with Google" on your app
  2. Redirected to Google login page
  3. User grants permission to your app
  4. Google sends authorization code to your app
  5. Your app exchanges code for access token
  6. Use access token to make API requests

Example: OAuth Request

// Step 1: Redirect user to OAuth provider const authUrl = `https://oauth.example.com/authorize?` + `client_id=YOUR_CLIENT_ID` + `&redirect_uri=https://yourapp.com/callback` + `&response_type=code` + `&scope=read_user read_posts`; window.location.href = authUrl; // Step 2: Exchange code for token (in callback) fetch('https://oauth.example.com/token', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ client_id: 'YOUR_CLIENT_ID', client_secret: 'YOUR_CLIENT_SECRET', code: authorizationCode, grant_type: 'authorization_code' }) }) .then(res => res.json()) .then(data => { const accessToken = data.access_token; // Use this token for API requests });

πŸ‘€ 4. Basic Authentication

Username and password encoded in Base64. Simple but less secure (only use with HTTPS!).

// JavaScript const username = 'myUsername'; const password = 'myPassword'; const credentials = btoa(`${username}:${password}`); // Base64 encode fetch('https://api.example.com/data', { headers: { 'Authorization': `Basic ${credentials}` } }) .then(res => res.json()) .then(data => console.log(data)); // cURL curl -u myUsername:myPassword https://api.example.com/data // Or manually with Base64 curl -H "Authorization: Basic bXlVc2VybmFtZTpteVBhc3N3b3Jk" \ https://api.example.com/data

πŸ›‘οΈ Security Best Practices

βœ… DO:

  • Use HTTPS (SSL/TLS) always
  • Store keys in environment variables
  • Rotate API keys regularly
  • Use token expiration
  • Implement rate limiting
  • Log authentication attempts

❌ DON'T:

  • Hard-code API keys in code
  • Commit keys to version control
  • Share keys via email/chat
  • Use same key across projects
  • Expose keys in client-side JS
  • Use HTTP (unencrypted)

🎯 API Strategy & Alignment

A sustainable API program starts with a clear strategy that aligns technical capabilities with business outcomes. This section provides a vendor-neutral overview (original content) of how successful teams plan and evolve APIs.

1. Vision & Value

  • Define target consumers (internal, partners, public)
  • Map APIs to revenue, retention or efficiency goals
  • Write one-line purpose statements per API

2. Portfolio Classification

  • Core domain APIs (billing, identity)
  • Enablement APIs (search, analytics)
  • Experience APIs (UI-focused aggregation)

3. Success Metrics

  • Adoption: active keys, calls / key
  • Quality: error %, latency percentiles
  • Business: conversions, partner retention

4. Evolution Roadmap

  • Quarterly version review
  • Deprecation policy & notice timeline
  • Feedback loop: surveys & support tickets
Governance Inputs to Strategy

Integrate cost controls, quota tiers, security classification (public vs confidential), and compliance requirements (PII, GDPR) at planning timeβ€”never as an afterthought.

πŸ”„ API Lifecycle

Managing APIs from Plan β†’ Design β†’ Build β†’ Secure β†’ Deploy β†’ Observe β†’ Iterate β†’ Deprecate reduces risk and improves developer experience.

PLAN

Identify domain boundaries, consumers, and measurable outcomes; capture use cases & non-functional requirements (performance, availability, compliance).

DESIGN

Model resources; define naming, versioning, error contracts, pagination. Validate with mock servers before implementation.

BUILD

Generate scaffolds, implement handlers, write unit & contract tests, add schema validation, enforce linting & spec review gates.

SECURE

Apply authentication (OAuth/JWT), authorization checks, input sanitization, rate limiting, audit logging; classify sensitive fields.

DEPLOY

Blue/green or canary releases; automated smoke tests; publish docs & changelog; announce availability channels.

OBSERVE

Collect metrics (latency p95, error rate, saturation), structured logs, distributed traces; correlate consumer adoption.

ITERATE

Address drift, performance hotspots, developer feedback; ship additive changes first before breaking changes.

DEPRECATE

Publish end-of-life timeline; dual-run versions; provide migration guides; enforce sunset headers near final phase.

Lifecycle Automation Tips
  • Use OpenAPI diff tooling to detect breaking changes
  • Emit structured events for key lifecycle transitions
  • Tag releases with semantic version & spec hash

πŸ›‘οΈ Governance & Security

Governance ensures consistency, risk management, and compliance across an expanding API surface.

Policy Catalog: Authentication standard, encryption-at-rest, allowed cipher suites, logging retention.
Design Review: Enforce naming, versioning, error format, pagination structure before merge.
Security Controls: Input validation, schema enforcement, WAF integration, anomaly alerting.
Risk Scoring: Higher scrutiny for PII, financial data, privileged operations.
Compliance Mapping: Link endpoints to GDPR/CCPA data categories for audit trails.
Change Management: Changelog automation + consumer notification (email, RSS, status page).
Operational Guardrails

Rate limits, burst limits, circuit breakers, and health probes form a resilience mesh that protects upstream services from overload and cascading failures.

πŸ’Ό API Monetization & Business Models

Transform APIs from pure technical enablers into measurable revenue or strategic leverage.

Freemium

Free tier builds adoption; paid tiers unlock higher quotas or premium datasets.

Usage-Based

Bill per call / per data unit; expose transparent dashboards for consumption.

Subscription

Flat monthly/annual fee for predictable access & support SLAs.

Revenue Share

Partners integrate and earn percentage on downstream transactions.

Internal ROI

Track saved engineering hours & productivity gains vs. legacy processes.

Monetization Checklist
  • Clear tiers & SLAs
  • Transparent quota & overage pricing
  • Self-service key provisioning
  • Real-time usage metrics
  • Automated invoicing & alerts

🧬 Integration Patterns

Common patterns help select the right approach for latency, consistency, scalability, and developer productivity.

SYNC Request/Response

Classic RESTful interaction; ideal for CRUD & immediate feedback. Beware chatty sequencesβ€”batch or aggregate where possible.

EVENT Publish/Subscribe

Emit domain events to decouple producers & consumers; improves scalability and supports reactive data flows.

STREAM WebSockets

Bi-directional low-latency updates for dashboards, collaborative editing, ad metrics, live bidding streams.

GATEWAY Aggregation

Gateway composes multiple backend services into simplified consumer-focused responses (Backend-for-Frontend).

CACHE Edge Caching

CDN or gateway layer caches immutable or slow-changing resources for latency reduction & cost control.

SCHEMA Contract First

Define OpenAPI/GraphQL schema before code; enables mock servers, rapid stakeholder validation, tooling generation.

Pattern Selection Guide

Start synchronous for simplicity; introduce events when scaling cross-service workflows; use aggregation to reduce mobile payload size; apply streaming for real-time personalization or monitoring dashboards.

πŸ“Š API Observability & Metrics

Monitor real-time health to catch issues early. These simulated values illustrate key indicators your production dashboards should expose.

Latency p95
-- ms
Error Rate
-- %
Throughput
-- rps
Apdex
--
CPU Saturation
-- %
Consumer Adoption
--
Metric Guidelines
  • Latency p95: Target < 300ms for core endpoints.
  • Error Rate: Keep under 1%; alert above 2%.
  • Throughput: Watch sudden drops (traffic loss) or spikes (abuse).
  • Apdex: Satisfaction score combining latency thresholds.
  • CPU Saturation: Sustained > 80% can cause tail latency.
  • Consumer Adoption: Weekly active keys; monitor onboarding funnel.
Tracing & Logging Tips

Use correlation IDs across services, structured JSON logs, and span tags (endpoint, version, user_tier) to accelerate root cause analysis during incidents.

js// OpenTelemetry (Node.js) basic instrumentation example import { NodeTracerProvider } from '@opentelemetry/sdk-trace-node'; import { SimpleSpanProcessor } from '@opentelemetry/sdk-trace-base'; import { ConsoleSpanExporter } from '@opentelemetry/sdk-trace-base'; import { registerInstrumentations } from '@opentelemetry/instrumentation'; import { HttpInstrumentation } from '@opentelemetry/instrumentation-http'; const provider = new NodeTracerProvider(); provider.addSpanProcessor(new SimpleSpanProcessor(new ConsoleSpanExporter())); provider.register(); registerInstrumentations({ instrumentations: [new HttpInstrumentation()] }); // Sample traced handler import express from 'express'; import { trace } from '@opentelemetry/api'; const app = express(); app.get('/api/blogs/:id', (req,res) => { const span = trace.getTracer('api-docs').startSpan('get.blog'); span.setAttribute('endpoint', '/api/blogs/:id'); span.setAttribute('blog.id', req.params.id); // Simulate work span.addEvent('cache.check'); span.end(); res.json({ id: req.params.id, status: 'ok' }); }); app.listen(3000); // Example span (JSON-like structure) /* { "traceId": "4f2c7e9b8d3a1f45e6b2a90123456789", "spanId": "9abc1245def67890", "name": "get.blog", "startTime": 1731739200123456, "endTime": 1731739200456789, "attributes": { "endpoint": "/api/blogs/:id", "blog.id": "42", "http.status_code": 200, "service.version": "v1.3.0" }, "events": [ { "name": "cache.check", "time": 1731739200130000 } ], "status": { "code": 1 }, "resource": { "service.name": "adtechupdate-api" } } */

⭐ API Development Best Practices

Industry-standard practices for building and consuming APIs like a professional.

Expand / Collapse Best Practices Content

1️⃣ Use Proper HTTP Methods

Method Use Case Idempotent? Has Body?
GET Retrieve data (read-only) βœ… Yes ❌ No
POST Create new resource ❌ No βœ… Yes
PUT Replace entire resource βœ… Yes βœ… Yes
PATCH Update part of resource ❌ No βœ… Yes
DELETE Remove resource βœ… Yes ❌ No

Idempotent: Making the same request multiple times has the same effect as making it once

2️⃣ Use Meaningful HTTP Status Codes

βœ… 2xx Success

  • 200 OK - Request succeeded
  • 201 Created - Resource created
  • 204 No Content - Success, no data returned

⚠️ 4xx Client Errors

  • 400 Bad Request - Invalid data
  • 401 Unauthorized - Not authenticated
  • 403 Forbidden - No permission
  • 404 Not Found - Resource doesn't exist
  • 429 Too Many Requests - Rate limited

❌ 5xx Server Errors

  • 500 Internal Server Error - Server crashed
  • 502 Bad Gateway - Invalid upstream response
  • 503 Service Unavailable - Server overloaded

πŸ”„ 3xx Redirects

  • 301 Moved Permanently - Resource moved
  • 302 Found - Temporary redirect
  • 304 Not Modified - Use cached version

3️⃣ Version Your API

Always version your API to avoid breaking changes for existing users.

Method 1: URL Path Versioning (Recommended)

https://api.example.com/v1/users https://api.example.com/v2/users // New version with breaking changes

Method 2: Header Versioning

GET https://api.example.com/users Accept: application/vnd.example.v1+json

Method 3: Query Parameter

https://api.example.com/users?version=1

4️⃣ Implement Pagination for Large Datasets

Never return thousands of records at once. Use pagination to improve performance.

Offset-Based Pagination

GET /users?limit=20&offset=40 // Get 20 users starting from #41 Response: { "data": [...], "pagination": { "total": 1000, "limit": 20, "offset": 40, "pages": 50, "current_page": 3 } }

Cursor-Based Pagination (Better for real-time data)

GET /posts?limit=20&cursor=eyJpZCI6MTIzfQ Response: { "data": [...], "pagination": { "next_cursor": "eyJpZCI6MTQzfQ", "has_more": true } }

5️⃣ Use Filtering, Sorting, and Searching

// Filtering GET /products?category=electronics&price_min=100&price_max=500 // Sorting GET /users?sort=created_at&order=desc // Searching GET /articles?q=javascript&tags=tutorial,beginner // Combining GET /products?category=electronics&sort=price&order=asc&limit=20

6️⃣ Rate Limiting

Protect your API from abuse by limiting requests per user/IP.

// Response headers HTTP/1.1 200 OK X-RateLimit-Limit: 100 // Max requests per hour X-RateLimit-Remaining: 87 // Requests left X-RateLimit-Reset: 1636449600 // When limit resets (Unix timestamp) // When limit exceeded HTTP/1.1 429 Too Many Requests Retry-After: 3600 // Retry after seconds { "error": "Rate limit exceeded", "message": "You've made too many requests. Please try again in 1 hour." }

7️⃣ Comprehensive Error Responses

// Bad: Vague error { "error": "Error occurred" } // Good: Detailed error with context { "status": "error", "code": 400, "error_type": "validation_error", "message": "Invalid input data", "errors": [ { "field": "email", "message": "Email format is invalid", "value": "notemail" }, { "field": "age", "message": "Age must be between 18 and 120", "value": 15 } ], "timestamp": "2025-11-12T10:30:00Z", "request_id": "req_abc123", "documentation_url": "https://api.example.com/docs/errors#validation_error" }

πŸ“‹ API Design Checklist

πŸ—οΈ Design

  • β˜‘οΈ Use RESTful conventions
  • β˜‘οΈ Use nouns for endpoints (not verbs)
  • β˜‘οΈ Use plural nouns (/users not /user)
  • β˜‘οΈ Use kebab-case for URLs
  • β˜‘οΈ Version your API

πŸ”’ Security

  • β˜‘οΈ Use HTTPS everywhere
  • β˜‘οΈ Implement authentication
  • β˜‘οΈ Validate all inputs
  • β˜‘οΈ Rate limiting
  • β˜‘οΈ CORS configuration

πŸ“Š Data

  • β˜‘οΈ Use JSON format
  • β˜‘οΈ Consistent naming (camelCase or snake_case)
  • β˜‘οΈ Include metadata
  • β˜‘οΈ Pagination for lists
  • β˜‘οΈ Allow filtering & sorting

πŸ“– Documentation

  • β˜‘οΈ Document all endpoints
  • β˜‘οΈ Provide code examples
  • β˜‘οΈ List all error codes
  • β˜‘οΈ Include authentication guide
  • β˜‘οΈ Keep docs up-to-date

Backend API Logic & Best Practices

Architecture Overview

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” HTTP Request β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ β”‚ ──────────────────────> β”‚ β”‚ β”‚ Client β”‚ β”‚ Server β”‚ β”‚ (Frontend) β”‚ <────────────────────── β”‚ (Backend) β”‚ β”‚ β”‚ HTTP Response β”‚ β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β”œβ”€β”€ Router β”œβ”€β”€ Middleware (Auth, Validation) β”œβ”€β”€ Controller (Business Logic) β”œβ”€β”€ Model (Data Layer) └── Database

Essential Components

1️⃣ Request Validation

// PHP Example function validateRequest($data, $rules) { $errors = []; foreach ($rules as $field => $rule) { if ($rule['required'] && empty($data[$field])) { $errors[] = "$field is required"; } if (isset($rule['type']) && gettype($data[$field]) !== $rule['type']) { $errors[] = "$field must be {$rule['type']}"; } } return empty($errors) ? true : $errors; }

2️⃣ Authentication & Authorization

// PHP Example - API Key Authentication function authenticateRequest() { $headers = getallheaders(); $apiKey = $headers['X-API-Key'] ?? ''; // Validate API key from database $validKey = validateApiKey($apiKey); if (!$validKey) { http_response_code(401); echo json_encode(['error' => 'Unauthorized']); exit; } return $validKey; }

3️⃣ Error Handling

// Standard error response format { "status": "error", "code": 400, "message": "Invalid request parameters", "errors": [ { "field": "email", "message": "Email format is invalid" } ], "timestamp": "2025-11-12T10:30:00Z" }

4️⃣ Rate Limiting

// Prevent API abuse function checkRateLimit($apiKey) { $redis = new Redis(); $key = "rate_limit:$apiKey"; $limit = 100; // requests per minute $current = $redis->incr($key); if ($current === 1) { $redis->expire($key, 60); } if ($current > $limit) { http_response_code(429); echo json_encode(['error' => 'Rate limit exceeded']); exit; } }

5️⃣ Response Formatting

// Consistent response structure function sendResponse($data, $statusCode = 200) { http_response_code($statusCode); header('Content-Type: application/json'); echo json_encode([ 'status' => $statusCode < 400 ? 'success' : 'error', 'data' => $data, 'timestamp' => date('c'), 'version' => 'v1.0' ]); }

Security Best Practices

  • Use HTTPS - Always encrypt data in transit
  • Validate Input - Never trust user input, sanitize everything
  • Implement Rate Limiting - Prevent abuse and DDoS attacks
  • Use API Keys/Tokens - Require authentication for sensitive endpoints
  • CORS Configuration - Control which domains can access your API
  • Error Messages - Don't expose sensitive information in errors
  • Logging - Track all API requests for debugging and security
  • Versioning - Use API versions to maintain backward compatibility

AdTech Update API Endpoints

Base URL: https://adtechupdate.space/pages/api.php

πŸ”’ Authentication Required: All endpoints require an API key. Pass it as ?key=YOUR_KEY or ?api_key=YOUR_KEY

Get All Data

GET

Retrieve all data from all tables when no table parameter is specified.

GET /pages/api.php?key=YOUR_API_KEY Host: adtechupdate.spaceAccept: application/json

Response Example

{ "blogs": [ { "id": 1, "name": "Programmatic Advertising Basics", "content": "Full content here...", "publisher": "AdTech Team", "created": "2025-01-15", "description": "Learn programmatic advertising" } ], "news": [...], "student_purchases": [...] }

Get Specific Table

GET

Retrieve data from specific table(s). Supports comma-separated table names.

GET /pages/api.php?key=YOUR_API_KEY&table=blogs&limit=10 Host: adtechupdate.spaceAccept: application/json

Query Parameters

Parameter Type Required Description
key string Required Your API key
table string Optional Table name: blogs, news, student_purchases, or "all"
limit integer Optional Number of records (1-1000, default: all)

Available Tables

  • blogs - Blog posts and articles
  • news - News articles
  • student_purchases - Student purchase records

Response Example

{ "blogs": [ { "id": 1, "name": "Header Bidding Explained", "content": "Comprehensive guide...", "publisher": "AdTech Team", "created": "2025-11-10", "description": "Understanding header bidding" }, { "id": 2, "name": "VAST and VPAID Comparison", "content": "Technical breakdown...", "publisher": "AdTech Team", "created": "2025-11-08", "description": "Video ad standards" } ] }

Custom SQL Query

GET

Execute custom SELECT queries (read-only, validated for security).

GET /pages/api.php?key=YOUR_API_KEY&sql=SELECT * FROM blogs WHERE id > 5 Host: adtechupdate.spaceAccept: application/json

Query Parameters

Parameter Type Required Description
key string Required Your API key
sql string Required SELECT query (INSERT/UPDATE/DELETE not allowed)

⚠️ Restrictions: Only SELECT queries allowed. No semicolons, comments, or modification statements (INSERT, UPDATE, DELETE, DROP, etc.)

Response Example

{ "query": "SELECT * FROM blogs WHERE id > 5", "rows": [ { "id": 6, "name": "Programmatic Trends 2025", "content": "...", "publisher": "AdTech Team", "created": "2025-11-05" } ] }

Describe Table Structure

GET

Get schema information for a specific table.

GET /pages/api.php?key=YOUR_API_KEY&describe=blogs Host: adtechupdate.spaceAccept: application/json

Response Example

{ "table": "blogs", "columns": [ { "COLUMN_NAME": "id", "DATA_TYPE": "int", "IS_NULLABLE": "NO", "COLUMN_DEFAULT": null, "CHARACTER_MAXIMUM_LENGTH": null, "COLUMN_KEY": "PRI" }, { "COLUMN_NAME": "name", "DATA_TYPE": "varchar", "IS_NULLABLE": "YES", "COLUMN_DEFAULT": null, "CHARACTER_MAXIMUM_LENGTH": 255, "COLUMN_KEY": "" } ] }

Get Summary Feed

GET

Retrieve aggregated summary with counts and featured content (cached for 5 minutes).

GET /pages/api.php?key=YOUR_API_KEY&summary=1&nocache=1 Host: adtechupdate.spaceAccept: application/json

Query Parameters

Parameter Type Required Description
key string Required Your API key
summary integer Required Set to 1 to enable summary
nocache integer Optional Set to 1 to bypass cache

Response Example

{ "counts": { "qa": 15, "cases": 8 }, "featured": [ { "type": "qa", "id": "rtb-basics", "title": "What is RTB?", "summary": "Real-Time Bidding explained...", "card_html": "
...
" }, { "type": "blog", "id": 1, "title": "Programmatic Advertising", "summary": "Guide to programmatic..." } ], "generated_at": "2025-11-12T10:30:00+00:00" }

Create Record (INSERT)

POST

Create new record in student_purchases table (requires owner API key).

POST /pages/api.php?key=OWNER_KEY&table=student_purchases Host: adtechupdate.spaceContent-Type: application/json { "student_id": 123, "course_id": 456, "amount": 99.99, "status": "completed" }

πŸ” Owner Key Required: Write operations require the owner API key and only work with table=student_purchases

Response Example

{ "success": true, "insert_id": 789 }

Update Record

PUT

Update existing record (requires owner API key).

PUT /pages/api.php?key=OWNER_KEY&table=student_purchases&id=789 Host: adtechupdate.spaceContent-Type: application/json { "status": "refunded", "refund_reason": "Customer request" }

Response Example

{ "success": true, "rows_affected": 1 }

Delete Record

DELETE

Delete existing record (requires owner API key).

DELETE /pages/api.php?key=OWNER_KEY&table=student_purchases&id=789 Host: adtechupdate.space

Response Example

{ "success": true, "rows_affected": 1 }

πŸ†• Additional API Endpoints

We provide multiple API protocols to suit your integration needs.

RESTful API (JSON)

GET POST PUT DELETE

Full CRUD operations with pagination, filtering, and search capabilities.

Base URL: https://adtechupdate.space/api/api-example.php

Example Requests

# Get all records with pagination GET https://adtechupdate.space/api/api-example.php?page=1&limit=10 # Get single record GET https://adtechupdate.space/api/api-example.php/1 # Filter by category and status GET https://adtechupdate.space/api/api-example.php?category=Privacy&status=published # Search records GET https://adtechupdate.space/api/api-example.php?search=programmatic # Create new record POST https://adtechupdate.space/api/api-example.php Content-Type: application/json { "title": "Understanding Header Bidding", "category": "Header Bidding", "author": "John Doe", "status": "draft" } # Update record PUT https://adtechupdate.space/api/api-example.php/1 Content-Type: application/json { "status": "published" } # Delete record DELETE https://adtechupdate.space/api/api-example.php/1

Features

  • βœ… Pagination support (page, limit)
  • βœ… Filtering by category, status
  • βœ… Full-text search
  • βœ… CORS enabled
  • βœ… Max 100 records enforced

Authentication

Pass your API key via header or query/body parameter. Writes require the owner key.

# Header options Authorization: Bearer YOUR_API_KEY # or Authorization: ApiKey YOUR_API_KEY # or X-API-Key: YOUR_API_KEY # Query param options GET https://adtechupdate.space/api/api-example.php?api_key=YOUR_API_KEY GET https://adtechupdate.space/api/api-example.php?key=YOUR_API_KEY # JSON body option (for POST/PUT) { "api_key": "YOUR_API_KEY" } # Notes: # - GET is public; providing an invalid key returns 401. # - POST/PUT/PATCH/DELETE require the OWNER key and return 403 otherwise.

GraphQL API

POST

Query exactly the data you need with flexible field selection.

Endpoint: https://adtechupdate.space/api/api-graphql.php

Query Examples

# Get all records with specific fields POST https://adtechupdate.space/api/api-graphql.php Content-Type: application/json { "query": "{ records { id title category status } }" } # Get single record { "query": "{ record(id: 1) { id title author created_at } }" } # Filter by category with limit { "query": "{ records(category: \"Privacy\", limit: 5) { title status } }" }

Mutation Examples

# Create record { "query": "mutation { createRecord(title: \"VAST vs VPAID\", category: \"Video Ads\") { id title } }" } # Update record { "query": "mutation { updateRecord(id: 1, status: \"published\") { id status updated_at } }" } # Delete record { "query": "mutation { deleteRecord(id: 1) { id title } }" }

Available Operations

  • Queries: records, record
  • Mutations: createRecord, updateRecord, deleteRecord
  • Arguments: id, category, status, limit, title, author

SOAP API (XML)

SOAP

Enterprise-grade XML-based protocol with WSDL support.

Endpoint: https://adtechupdate.space/api/api-soap.php
WSDL: https://adtechupdate.space/api/api-soap.php?wsdl

Available Methods

  • getRecords($category, $status, $limit) - Get all records
  • getRecord($id) - Get single record
  • createRecord($title, $category, $author, $status) - Create new
  • updateRecord($id, $title, $category, $author, $status) - Update existing
  • deleteRecord($id) - Delete record

PHP Client Example