API Documentation

Welcome to our API documentation. This guide will help you integrate with our OAuth 2.0 API.


Getting Started

To use our API, you need to register your application and implement the OAuth 2.0 authorization flow.

Register Your Application

Before you can use our API, you need to register your application:

  1. Go to the API Client Registration page
  2. Fill out the registration form with your application details
  3. After registration, you'll receive a client_id and client_secret
  4. Important: Store your client secret securely as it won't be displayed again

OAuth 2.0 Authorization Flow

Our API uses the OAuth 2.0 Authorization Code flow, which involves the following steps:

Step 1: Authorization Request

Direct your users to our authorization endpoint.

Step 2: User Authentication

The user will be prompted to log in (if not already) and grant permission to your application.

Step 3: Authorization Code

After authorization, the user will be redirected to your specified redirect URI with an authorization code.

Step 4: Token Exchange

Exchange the authorization code for an access token.

Step 5: API Requests

Use the access token to make authenticated API requests.

Authorization

Our API uses OAuth 2.0 authorization to securely authenticate users and applications.

Authorize Endpoint

GET
/api/authorize.php

Redirects the user to our authentication page where they can approve access for your application.

Parameters
Parameter Type Required Description
client_id string Yes Your application's client ID
redirect_uri string Yes The URI to redirect to after authorization (must match the one registered)
response_type string Yes Must be set to code
Example Request
GET /api/authorize.php?client_id=YOUR_CLIENT_ID&redirect_uri=https://example.com/callback&response_type=code

Token Endpoint

POST
/api/token.php

Exchanges an authorization code for an access token.

Parameters
Parameter Type Required Description
code string Yes The authorization code received from the authorize endpoint
client_id string Yes Your application's client ID
client_secret string Yes Your application's client secret
Example Request
POST /api/token.php
Content-Type: application/x-www-form-urlencoded

code=AUTHORIZATION_CODE&client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET
Example Response
{
  "access_token": "ACCESS_TOKEN",
  "token_type": "Bearer",
  "expires_in": 3600
}

API Endpoints

Once you have an access token, you can use it to access our API endpoints.

User Info Endpoint

GET
/api/userinfo.php

Returns information about the authenticated user.

Headers
Header Value Required Description
Authorization Bearer ACCESS_TOKEN Yes The access token obtained from the token endpoint
Example Request
GET /api/userinfo.php
Authorization: Bearer ACCESS_TOKEN
Example Response
{
  "username": "johndoe",
  "email": "john@example.com",
  "full_name": "John Doe"
}

Error Handling

API errors are returned with appropriate HTTP status codes and a JSON response.

{
  "error": "error_code",
  "error_description": "Human-readable description"
}
Error Code HTTP Status Description
invalid_request 400 The request is missing required parameters
invalid_client 401 Client authentication failed
invalid_code 400 The authorization code is invalid or expired
invalid_token 401 The access token is invalid or expired

Rate Limits

Our API implements rate limiting to ensure service availability for all users:

  • 60 requests per minute for most endpoints
  • 5 requests per minute for token generation endpoints

When rate limits are exceeded, the API will return a 429 Too Many Requests status code with headers indicating the rate limit and when you can retry.

Best Practices

  1. Security: Always use HTTPS for all API communication
  2. Client Secret: Never expose your client secret in client-side code
  3. Redirect URIs: Validate all redirect URIs to prevent open redirects
  4. CSRF Protection: Implement CSRF protection for the authorization flow
  5. Token Storage: Do not store access tokens in local storage; use secure HTTP-only cookies
  6. Token Management: Implement token rotation and expiration handling
  7. Error Handling: Implement proper error handling for all API calls
  8. Retry Logic: Add retry logic with exponential backoff for transient errors
  9. Caching: Cache frequently accessed data to minimize API calls
  10. Input Validation: Validate all user input before sending it to the API

Code Examples

<?php
// Step 1: Redirect user to authorization endpoint
$authUrl = 'https://example.com/api/authorize.php?' . http_build_query([
    'client_id' => 'YOUR_CLIENT_ID',
    'redirect_uri' => 'YOUR_REDIRECT_URI',
    'response_type' => 'code'
]);
header("Location: $authUrl");
exit;

// Step 2: Handle the authorization code (on your redirect URI page)
if (isset($_GET['code'])) {
    $code = $_GET['code'];
    
    // Step 3: Exchange the code for an access token
    $ch = curl_init('https://example.com/api/token.php');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([
        'code' => $code,
        'client_id' => 'YOUR_CLIENT_ID',
        'client_secret' => 'YOUR_CLIENT_SECRET'
    ]));
    
    $response = curl_exec($ch);
    curl_close($ch);
    
    $tokenData = json_decode($response, true);
    $accessToken = $tokenData['access_token'];
    
    // Step 4: Use the access token to make API requests
    $ch = curl_init('https://example.com/api/userinfo.php');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Authorization: Bearer ' . $accessToken
    ]);
    
    $userData = curl_exec($ch);
    curl_close($ch);
    
    // Process user data
    $user = json_decode($userData, true);
    echo "Hello, " . $user['username'];
}
?>
// Step 1: Redirect user to authorization endpoint
function authorize() {
    const authUrl = 'https://example.com/api/authorize.php?' + 
        new URLSearchParams({
            client_id: 'YOUR_CLIENT_ID',
            redirect_uri: 'YOUR_REDIRECT_URI',
            response_type: 'code'
        });
    
    window.location.href = authUrl;
}

// Step 2: Handle the authorization code (on your redirect URI page)
async function handleRedirect() {
    const urlParams = new URLSearchParams(window.location.search);
    const code = urlParams.get('code');
    
    if (code) {
        // Step 3: Exchange the code for an access token (via your backend)
        const tokenResponse = await fetch('/your-backend-endpoint', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ code })
        });
        
        const tokenData = await tokenResponse.json();
        const accessToken = tokenData.access_token;
        
        // Step 4: Use the access token to make API requests
        const userResponse = await fetch('https://example.com/api/userinfo.php', {
            headers: {
                'Authorization': `Bearer ${accessToken}`
            }
        });
        
        const userData = await userResponse.json();
        console.log('User data:', userData);
    }
}
import requests
from flask import Flask, request, redirect, session
import os

app = Flask(__name__)
app.secret_key = os.urandom(24)

# Configuration
CLIENT_ID = 'YOUR_CLIENT_ID'
CLIENT_SECRET = 'YOUR_CLIENT_SECRET'
REDIRECT_URI = 'YOUR_REDIRECT_URI'
AUTH_URL = 'https://example.com/api/authorize.php'
TOKEN_URL = 'https://example.com/api/token.php'
API_URL = 'https://example.com/api/userinfo.php'

@app.route('/login')
def login():
    # Step 1: Redirect user to authorization endpoint
    auth_params = {
        'client_id': CLIENT_ID,
        'redirect_uri': REDIRECT_URI,
        'response_type': 'code'
    }
    auth_url = f"{AUTH_URL}?{'&'.join(f'{k}={v}' for k, v in auth_params.items())}"
    return redirect(auth_url)

@app.route('/callback')
def callback():
    # Step 2: Handle the authorization code
    code = request.args.get('code')
    
    if code:
        # Step 3: Exchange the code for an access token
        token_data = {
            'code': code,
            'client_id': CLIENT_ID,
            'client_secret': CLIENT_SECRET
        }
        
        token_response = requests.post(TOKEN_URL, data=token_data)
        token_json = token_response.json()
        
        if 'access_token' in token_json:
            # Store the token in session
            session['access_token'] = token_json['access_token']
            
            # Step 4: Use the access token to make API requests
            return redirect('/profile')
    
    return "Authorization failed", 400

@app.route('/profile')
def profile():
    # Check if user is authenticated
    if 'access_token' not in session:
        return redirect('/login')
    
    # Make API request to get user info
    headers = {
        'Authorization': f"Bearer {session['access_token']}"
    }
    
    response = requests.get(API_URL, headers=headers)
    
    if response.status_code == 200:
        user_data = response.json()
        return f"Hello, {user_data['username']}! Your email is {user_data['email']}"
    else:
        session.pop('access_token', None)
        return redirect('/login')

if __name__ == '__main__':
    app.run(debug=True)

Getting Support

If you need help with our API or have any questions, please contact our developer support team:

Developer Support

Our support team is available Monday through Friday, 9 AM to 5 PM (UTC).

Stay Updated

Subscribe to our developer newsletter to receive updates about new features, deprecations, and best practices.

Subscribe to Newsletter