API Reference: Introduction

This comprehensive reference guide provides detailed information about our API endpoints, request/response formats, error handling, and other key aspects of the MyAppAPI platform. Whether you're building a simple integration or a complex application, this documentation will help you effectively utilize our API.

API Base URL
https://api.myappapi.com/v1
Current Version
v1 (Stable)
Data Format
JSON
Authentication
API Keys, OAuth 2.0, JWT

API Architecture

MyAppAPI follows REST (Representational State Transfer) principles to provide a scalable and predictable API experience. Our architecture is designed with the following key considerations:

RESTful Design

Our API is built on standard REST conventions, making it intuitive and easy to use. The key characteristics include:

  • Resource-oriented URLs - Endpoints are organized around resources, with URL paths that clearly identify the resource being accessed.
  • Standard HTTP methods - We use standard HTTP methods (GET, POST, PUT, DELETE, PATCH) to perform operations on resources.
  • Stateless interactions - Each API request contains all the information needed to process it, with no reliance on server-side session state.
  • Consistent resource representations - Resources have consistent representations across the API, promoting predictability.

GraphQL Support

In addition to our RESTful API, we offer a GraphQL endpoint for clients that need more flexibility in specifying exactly what data they want to retrieve or modify. The GraphQL API is available at:

https://api.myappapi.com/graphql

Our GraphQL implementation offers several advantages:

  • Flexible data retrieval - Request exactly the data you need in a single API call
  • Strongly-typed schema - The API schema is self-documenting and validates requests
  • Efficient data loading - Reduces over-fetching and under-fetching of data
  • Real-time subscriptions - Subscribe to data changes for real-time updates

WebSocket API

For real-time communications, we provide a WebSocket API that allows clients to establish a persistent connection with our servers. This is particularly useful for:

  • Real-time data streaming - Receive data updates as they happen
  • Bi-directional communication - Send and receive messages over the same connection
  • Reduced latency - No need to establish a new connection for each message
  • Lower overhead - Less header data compared to HTTP requests

The WebSocket API is available at:

wss://api.myappapi.com/v1/websocket

API Versioning

Our API uses a versioning scheme to ensure that changes to the API don't break existing client integrations. Understanding our versioning approach will help you build more stable applications:

Version Format

API versions are specified in the URL path (e.g., /v1/resources). This makes the version explicit and ensures that your requests target a specific API version.

Version Lifecycle

Each API version goes through the following lifecycle stages:

  1. Preview - Early access to new features, subject to change without notice
  2. Stable - Production-ready with backward compatibility guarantees
  3. Deprecated - Scheduled for eventual retirement, with migration paths specified
  4. Retired - No longer available for use

Current Versions

Version Status Released End of Life
v1 Stable January 2024 No planned retirement
v2-preview Preview March 2025 N/A

Backward Compatibility

For stable API versions, we maintain backward compatibility according to these principles:

  • We don't remove fields from API responses
  • We don't change the semantics of existing fields
  • We don't add required request parameters
  • We maintain existing endpoint URLs

We may add new endpoints, new optional parameters, or new fields in responses without changing the API version, as these changes don't break existing clients.

Version Migration

When a new major version (e.g., v2) is released, we provide:

  • Detailed migration guides
  • Overlap periods where both versions are supported
  • Clear timelines for deprecation of older versions
  • Tools to help test your integration with new versions

We recommend subscribing to our changelog to stay informed about API updates and new versions.

Request Format

This section covers the standard formats and conventions for making requests to our API.

HTTP Methods

Our API uses standard HTTP methods to perform different operations on resources:

Method Description Example
GET Retrieve data, never modifies resources GET /v1/users - Lists users
POST Create a new resource or trigger actions POST /v1/users - Creates a new user
PUT Update a resource by replacing it entirely PUT /v1/users/123 - Replaces user data
PATCH Partially update a resource PATCH /v1/users/123 - Updates specific user fields
DELETE Remove a resource DELETE /v1/users/123 - Deletes a user

Headers

The following HTTP headers are commonly used with our API:

Content-Type: application/json
Accept: application/json
Authorization: Bearer YOUR_API_KEY
X-API-Version: 1
X-Request-ID: your-correlation-id

Common Headers

  • Content-Type: Specifies the format of the request body. For most operations, this should be application/json.
  • Accept: Specifies the expected response format. We recommend setting this to application/json.
  • Authorization: Contains the authentication credentials. For API key authentication, use Bearer YOUR_API_KEY.
  • X-API-Version: Optional header to specify the API version. This can be used instead of or in addition to the version in the URL path.
  • X-Request-ID: Optional client-generated ID for request correlation. If provided, we'll include this ID in response headers and logs for troubleshooting.

Request Body

For methods that require a request body (POST, PUT, PATCH), the data should be formatted as JSON. Here's an example request to create a new user:

POST /v1/users HTTP/1.1
Host: api.myappapi.com
Content-Type: application/json
Authorization: Bearer YOUR_API_KEY

{
  "name": "Jane Smith",
  "email": "[email protected]",
  "role": "admin",
  "metadata": {
    "department": "Engineering",
    "location": "Remote"
  }
}

Query Parameters

GET requests often include query parameters to filter, sort, or paginate results. For example:

GET /v1/users?limit=10&offset=20&sort=created_at:desc&status=active

Common query parameters include:

  • limit: Maximum number of items to return (default: 20, max: 100)
  • offset: Number of items to skip (for pagination)
  • sort: Field to sort by, with optional direction (asc or desc)
  • fields: Comma-separated list of fields to include in the response
  • expand: Comma-separated list of related resources to expand

Endpoint-specific parameters are documented in the individual endpoint reference pages.

Filtering

Many list endpoints support filtering results based on resource attributes. Filters can be applied using query parameters:

GET /v1/users?status=active&role=admin&created_at[gte]=2023-01-01

For more complex filtering, you can use operators:

  • [eq]: Equal to (default if no operator is specified)
  • [neq]: Not equal to
  • [gt]: Greater than
  • [gte]: Greater than or equal to
  • [lt]: Less than
  • [lte]: Less than or equal to
  • [in]: Included in a comma-separated list
  • [nin]: Not included in a comma-separated list
  • [like]: Pattern matching (uses % as wildcard)

Example with operators:

GET /v1/users?created_at[gte]=2023-01-01&role[in]=admin,editor&name[like]=%smith%

Response Format

This section covers the standard formats for API responses and how to interpret them.

Response Structure

All API responses follow a consistent JSON format with these top-level fields:

{
  "data": {
    // The main response data (object or array)
  },
  "meta": {
    // Metadata about the response
    "request_id": "req_1234567890",
    "pagination": {
      "total": 100,
      "limit": 10,
      "offset": 0,
      "next": "/v1/resources?limit=10&offset=10",
      "previous": null
    }
  },
  "error": {
    // Only present if there was an error
    "code": "error_code",
    "message": "Human-readable error message",
    "details": {
      // Additional error details
    }
  }
}

Success Response Fields

  • data: Contains the main response data. For single-resource operations, this is an object. For list operations, this is an array of objects.
  • meta: Contains metadata about the request and response, such as pagination information, request ID, and timing details.

Error Response Fields

  • error: Present only when an error occurs. Contains information about the error including a machine-readable code, a human-readable message, and additional details when applicable.

HTTP Status Codes

Our API uses standard HTTP status codes to indicate the success or failure of an API request:

Success Codes

  • 200 OK: The request was successful and resource(s) were returned
  • 201 Created: The request was successful and a new resource was created
  • 202 Accepted: The request was accepted for processing, but processing may not be complete
  • 204 No Content: The request was successful but there is no content to return

Client Error Codes

  • 400 Bad Request: The request was malformed or contained invalid parameters
  • 401 Unauthorized: Authentication is required or failed
  • 403 Forbidden: The authenticated user doesn't have permission to access the resource
  • 404 Not Found: The requested resource doesn't exist
  • 409 Conflict: The request conflicts with the current state of the resource
  • 422 Unprocessable Entity: The request was well-formed but contains semantic errors
  • 429 Too Many Requests: The client has sent too many requests in a given time period

Server Error Codes

  • 500 Internal Server Error: An error occurred on the server
  • 502 Bad Gateway: The server received an invalid response from an upstream server
  • 503 Service Unavailable: The server is temporarily unavailable
  • 504 Gateway Timeout: An upstream server timed out

Pagination

List operations support pagination to limit the number of results returned in a single response. The pagination information is included in the meta.pagination field:

{
  "data": [
    // Array of resources
  ],
  "meta": {
    "pagination": {
      "total": 243,      // Total number of records matching the query
      "limit": 20,       // Number of records requested per page
      "offset": 40,      // Number of records skipped
      "next": "/v1/resources?limit=20&offset=60",   // URL for the next page
      "previous": "/v1/resources?limit=20&offset=20" // URL for the previous page
    }
  }
}

To paginate through results, use the limit and offset query parameters:

GET /v1/resources?limit=20&offset=40

For convenience, the next and previous URLs in the pagination object can be used directly to navigate between pages. These values will be null when there is no next or previous page.

Response Headers

Our API includes several custom headers in responses:

  • X-Request-ID: A unique identifier for the request, useful for troubleshooting
  • X-RateLimit-Limit: The maximum number of requests allowed in the current period
  • X-RateLimit-Remaining: The number of requests remaining in the current period
  • X-RateLimit-Reset: The time at which the current rate limit period resets (Unix timestamp)
  • X-Response-Time: The time taken to process the request on the server (ms)

API Resources

Our API is organized around resources, which represent the various entities and concepts in our system. Below is an overview of the main resources available through the API:

Users

Create, read, update, and delete user accounts. Manage user profiles, authentication, and permissions.

GET /v1/users
POST /v1/users
GET /v1/users/:id

Resources

Manage the primary resources in your application. Create, retrieve, update, and delete resources and their data.

GET /v1/resources
POST /v1/resources
PUT /v1/resources/:id

Webhooks

Configure webhooks to receive real-time notifications about events in your account. Manage subscription endpoints and delivery settings.

GET /v1/webhooks
POST /v1/webhooks
DELETE /v1/webhooks/:id

Events

Access the event stream for your account. Retrieve historical events and logs for auditing and monitoring purposes.

GET /v1/events
GET /v1/events/:id

Each resource has its own dedicated documentation page with detailed information about the available endpoints, request and response formats, and examples.

Code Examples

Below are examples of how to use our API with various programming languages and frameworks. These examples demonstrate basic API usage patterns that you can adapt for your specific needs.

Making a request with cURL

curl -X GET "https://api.myappapi.com/v1/resources" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Accept: application/json"

Creating a resource with cURL

curl -X POST "https://api.myappapi.com/v1/resources" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Accept: application/json" \
  -d '{
    "name": "Example Resource",
    "description": "This is an example resource",
    "type": "standard",
    "metadata": {
      "category": "examples",
      "tags": ["api", "documentation"]
    }
  }'

JavaScript/Node.js Example

// Using fetch (browser or Node.js with node-fetch)
const apiKey = 'YOUR_API_KEY';
const baseUrl = 'https://api.myappapi.com/v1';

// Get resources
async function getResources() {
  const response = await fetch(`${baseUrl}/resources`, {
    method: 'GET',
    headers: {
      'Authorization': `Bearer ${apiKey}`,
      'Content-Type': 'application/json',
      'Accept': 'application/json'
    }
  });
  
  if (!response.ok) {
    throw new Error(`API error: ${response.status}`);
  }
  
  const data = await response.json();
  return data;
}

// Create a resource
async function createResource(resourceData) {
  const response = await fetch(`${baseUrl}/resources`, {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${apiKey}`,
      'Content-Type': 'application/json',
      'Accept': 'application/json'
    },
    body: JSON.stringify(resourceData)
  });
  
  if (!response.ok) {
    const errorData = await response.json();
    throw new Error(errorData.error?.message || `API error: ${response.status}`);
  }
  
  const data = await response.json();
  return data;
}

Python Example

import requests

api_key = 'YOUR_API_KEY'
base_url = 'https://api.myappapi.com/v1'

headers = {
    'Authorization': f'Bearer {api_key}',
    'Content-Type': 'application/json',
    'Accept': 'application/json'
}

# Get resources
def get_resources():
    response = requests.get(f'{base_url}/resources', headers=headers)
    response.raise_for_status()  # Raise exception for 4XX/5XX responses
    return response.json()

# Create a resource
def create_resource(resource_data):
    response = requests.post(
        f'{base_url}/resources',
        headers=headers,
        json=resource_data  # Automatically serializes to JSON
    )
    response.raise_for_status()
    return response.json()

# Example usage
try:
    # Get all resources
    resources = get_resources()
    print(f"Found {len(resources['data'])} resources")
    
    # Create a new resource
    new_resource = create_resource({
        'name': 'Example Resource',
        'description': 'Created with Python',
        'type': 'standard'
    })
    print(f"Created resource with ID: {new_resource['data']['id']}")
    
except requests.exceptions.RequestException as e:
    print(f"API Error: {e}")

Ruby Example

require 'net/http'
require 'uri'
require 'json'

api_key = 'YOUR_API_KEY'
base_url = 'https://api.myappapi.com/v1'

# Common headers
headers = {
  'Authorization' => "Bearer #{api_key}",
  'Content-Type' => 'application/json',
  'Accept' => 'application/json'
}

# Get resources
def get_resources
  uri = URI("#{base_url}/resources")
  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = (uri.scheme == 'https')
  
  request = Net::HTTP::Get.new(uri, headers)
  response = http.request(request)
  
  if response.code.to_i >= 200 && response.code.to_i < 300
    JSON.parse(response.body)
  else
    error = JSON.parse(response.body) rescue nil
    error_message = error&.dig('error', 'message') || "HTTP Error: #{response.code}"
    raise error_message
  end
end

# Create a resource
def create_resource(resource_data)
  uri = URI("#{base_url}/resources")
  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = (uri.scheme == 'https')
  
  request = Net::HTTP::Post.new(uri, headers)
  request.body = resource_data.to_json
  response = http.request(request)
  
  if response.code.to_i >= 200 && response.code.to_i < 300
    JSON.parse(response.body)
  else
    error = JSON.parse(response.body) rescue nil
    error_message = error&.dig('error', 'message') || "HTTP Error: #{response.code}"
    raise error_message
  end
end

# Example usage
begin
  resources = get_resources
  puts "Found #{resources['data'].length} resources"
  
  new_resource = create_resource({
    name: 'Example Resource',
    description: 'Created with Ruby',
    type: 'standard'
  })
  puts "Created resource with ID: #{new_resource['data']['id']}"
rescue => e
  puts "Error: #{e.message}"
end

PHP Example

<?php
$apiKey = 'YOUR_API_KEY';
$baseUrl = 'https://api.myappapi.com/v1';

// Common headers
$headers = [
    'Authorization: Bearer ' . $apiKey,
    'Content-Type: application/json',
    'Accept: application/json'
];

// Get resources
function getResources($baseUrl, $headers) {
    $ch = curl_init($baseUrl . '/resources');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    
    $response = curl_exec($ch);
    $statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    if ($statusCode >= 200 && $statusCode < 300) {
        return json_decode($response, true);
    } else {
        $error = json_decode($response, true);
        $errorMessage = isset($error['error']['message']) 
            ? $error['error']['message'] 
            : 'HTTP Error: ' . $statusCode;
        throw new Exception($errorMessage);
    }
}

// Create a resource
function createResource($baseUrl, $headers, $resourceData) {
    $ch = curl_init($baseUrl . '/resources');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($resourceData));
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    
    $response = curl_exec($ch);
    $statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    if ($statusCode >= 200 && $statusCode < 300) {
        return json_decode($response, true);
    } else {
        $error = json_decode($response, true);
        $errorMessage = isset($error['error']['message']) 
            ? $error['error']['message'] 
            : 'HTTP Error: ' . $statusCode;
        throw new Exception($errorMessage);
    }
}

// Example usage
try {
    $resources = getResources($baseUrl, $headers);
    echo 'Found ' . count($resources['data']) . ' resources' . PHP_EOL;
    
    $newResource = createResource($baseUrl, $headers, [
        'name' => 'Example Resource',
        'description' => 'Created with PHP',
        'type' => 'standard'
    ]);
    echo 'Created resource with ID: ' . $newResource['data']['id'] . PHP_EOL;
} catch (Exception $e) {
    echo 'Error: ' . $e->getMessage() . PHP_EOL;
}
?>

Java Example

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

public class MyAppApiExample {
    private static final String API_KEY = "YOUR_API_KEY";
    private static final String BASE_URL = "https://api.myappapi.com/v1";
    
    public static void main(String[] args) {
        try {
            // Get resources
            String resources = getResources();
            System.out.println("Resources retrieved successfully");
            
            // Create a resource
            String resourceData = "{"
                + "\"name\": \"Example Resource\","
                + "\"description\": \"Created with Java\","
                + "\"type\": \"standard\""
                + "}";
            String newResource = createResource(resourceData);
            System.out.println("Resource created successfully");
            
        } catch (IOException e) {
            System.err.println("API Error: " + e.getMessage());
        }
    }
    
    private static String getResources() throws IOException {
        URL url = new URL(BASE_URL + "/resources");
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setRequestProperty("Authorization", "Bearer " + API_KEY);
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Accept", "application/json");
        
        int responseCode = connection.getResponseCode();
        if (responseCode >= 200 && responseCode < 300) {
            BufferedReader reader = new BufferedReader(
                new InputStreamReader(connection.getInputStream())
            );
            StringBuilder response = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            reader.close();
            return response.toString();
        } else {
            throw new IOException("HTTP Error: " + responseCode);
        }
    }
    
    private static String createResource(String data) throws IOException {
        URL url = new URL(BASE_URL + "/resources");
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Authorization", "Bearer " + API_KEY);
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Accept", "application/json");
        connection.setDoOutput(true);
        
        try (OutputStream os = connection.getOutputStream()) {
            byte[] input = data.getBytes(StandardCharsets.UTF_8);
            os.write(input, 0, input.length);
        }
        
        int responseCode = connection.getResponseCode();
        if (responseCode >= 200 && responseCode < 300) {
            BufferedReader reader = new BufferedReader(
                new InputStreamReader(connection.getInputStream())
            );
            StringBuilder response = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            reader.close();
            return response.toString();
        } else {
            throw new IOException("HTTP Error: " + responseCode);
        }
    }
}

Next Steps

Now that you understand the fundamentals of our API, you can explore the detailed documentation for each specific resource and feature. We recommend the following resources to continue your journey:

Authentication Guide

Learn about the different authentication methods supported by our API and how to implement them securely.

Error Handling

Understand our error codes and learn best practices for handling errors in your API integrations.

Rate Limits

Learn about our rate limiting policies and how to optimize your API usage to avoid hitting limits.

Interactive API Explorer

Try out the API directly in your browser with our interactive API Explorer tool.

Frequently Asked Questions

How do I report a bug or issue with the API?

If you encounter any issues or bugs with our API, please report them through our support portal. Include as much detail as possible, including the specific API endpoint, request details, error messages, and steps to reproduce the issue. You can also check our status page to see if there are any known service disruptions.

How do I increase my API rate limits?

Rate limits are determined by your subscription plan. To increase your rate limits, you can upgrade your plan through the billing section of your dashboard. If you have specific needs that aren't covered by our standard plans, please contact our sales team to discuss custom options.

Does the API support cross-origin requests (CORS)?

Yes, our API supports Cross-Origin Resource Sharing (CORS) for browser-based applications. We allow requests from any origin by default, but you can restrict allowed origins in your security settings. CORS preflight requests (OPTIONS) do not count against your rate limits.

How long are API keys valid?

API keys do not expire automatically, but we recommend rotating them periodically as a security best practice. You can create new API keys and revoke existing ones at any time through the API Keys section of your dashboard. For increased security, consider using short-lived JWT tokens instead of long-lived API keys.

How can I test the API without affecting production data?

We provide a sandbox environment for testing your integrations without affecting production data. The sandbox environment is available at https://sandbox-api.myappapi.com/v1 and functions identically to the production API. You'll need separate API keys for the sandbox environment, which you can create in the Sandbox section of your dashboard.