What is MatchGraph?

MatchGraph is a powerful platform that transforms raw football match data into actionable insights. Our API allows you to:

Query Match Data

Access comprehensive match statistics, player performance metrics, and event data through natural language queries.

Video Analysis

Generate video clips of specific events, player actions, and match highlights with automated annotation.

Advanced Analytics

Leverage machine learning models for player scouting, performance prediction, and tactical analysis.

Real-time Data

Get live match data, player tracking information, and instant notifications through webhooks.

API Interfaces

MatchGraph offers three different ways to interact with your data:

Natural Language API

Query your data using plain English. Perfect for non-technical users and rapid prototyping.

Example Query
Show me all goals and assists by player 9 in the last 5 matches

GraphQL API

Flexible querying with strong typing and efficient data fetching. Ideal for complex applications.

Example Query
query PlayerEvents {
  events(
    playerId: "9"
    eventType: [GOAL, ASSIST]
    limit: 5
  ) {
    matchId
    timestamp
    type
    position
    details
  }
}

REST API

Traditional REST endpoints with JSON responses. Simple and familiar for most developers.

Example Request
curl -X GET "https://api.matchgraph.io/v1/events?playerId=9&eventType=GOAL,ASSIST&limit=5" \
  -H "Authorization: Bearer YOUR_API_KEY"

Key Features

Secure & Reliable

Enterprise-grade security with API key authentication, rate limiting, and 99.9% uptime SLA.

Global Coverage

Data from major leagues worldwide including Premier League, La Liga, Bundesliga, and more.

Real-time Updates

Live match data with sub-second latency and webhook notifications for instant updates.

Developer Friendly

Comprehensive documentation, SDKs for multiple languages, and interactive API explorer.

Getting Started

Ready to start using the MatchGraph API? Follow these steps:

1

Sign Up for an Account

Create your MatchGraph account and verify your email address.

2

Generate API Keys

Navigate to your dashboard and create API keys for your applications.

3

Choose Your Interface

Decide whether to use Natural Language, GraphQL, or REST API based on your needs.

4

Make Your First Request

Follow our quick start guide to make your first API call and see data in action.

Prerequisites

Before you begin, make sure you have:

  • A MatchGraph account (sign up at matchgraph.io)
  • An API key from your dashboard
  • Basic knowledge of HTTP requests and JSON

Step 1: Authentication

All API requests require authentication using your API key. Include it in the Authorization header:

Authentication Header
Authorization: Bearer YOUR_API_KEY_HERE

Step 2: Your First Request

Let's start with a simple request to get player statistics:

REST API Example
curl -X GET "https://api.matchgraph.io/v1/players/9/stats" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json"

This request will return player statistics for player ID 9. The response will include performance metrics, match data, and more.

Step 3: Natural Language Query

For a more intuitive approach, try our Natural Language API:

Natural Language Example
{
  "query": "Show me all goals and assists by player 9 in the last 5 matches",
  "format": "json"
}

Send this to the Natural Language endpoint:

Natural Language Request
curl -X POST "https://api.matchgraph.io/v1/query" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "query": "Show me all goals and assists by player 9 in the last 5 matches",
    "format": "json"
  }'

Step 4: GraphQL Query

For more complex queries, use our GraphQL API:

GraphQL Example
query PlayerPerformance {
  playerStats(playerId: "9", matchCount: 5) {
    matchesAnalyzed
    performanceMetrics {
      shooting {
        totalShots
        onTarget
        accuracy
        goals
        xG
      }
      passing {
        totalPasses
        completed
        completionRate
        throughBalls {
          attempted
          successful
          successRate
        }
      }
      physical {
        distanceCovered
        averageSpeed
        maxSpeed
        sprints
      }
    }
    teamComparison {
      shotAccuracy
      passCompletion
      distanceCovered
    }
  }
}

Send this to the GraphQL endpoint:

GraphQL Request
curl -X POST "https://api.matchgraph.io/v1/graphql" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "query": "query PlayerPerformance { playerStats(playerId: \"9\", matchCount: 5) { matchesAnalyzed performanceMetrics { shooting { totalShots accuracy goals xG } passing { completionRate throughBalls { successRate } } } } }"
  }'

Next Steps

Now that you've made your first API calls, explore these resources:

Explore Data Models

Learn about the structure of events, players, teams, and matches.

View Data Models

Try Query Examples

See practical examples of common API use cases.

View Examples

Check Rate Limits

Understand API limits and best practices for production use.

View Limits

API Keys

MatchGraph uses API key authentication for all requests. You can generate API keys from your dashboard.

Keep Your Keys Secure

Never expose your API keys in client-side code or public repositories. Use environment variables or secure key management systems.

Using API Keys

Include your API key in the Authorization header of every request:

Authorization Header
Authorization: Bearer YOUR_API_KEY_HERE

Example Request

Complete Request
curl -X GET "https://api.matchgraph.io/v1/players/9/stats" \
  -H "Authorization: Bearer mg_live_1234567890abcdef" \
  -H "Content-Type: application/json"

Key Management

Manage your API keys from the MatchGraph dashboard:

Creating Keys

  1. Log in to your MatchGraph dashboard
  2. Navigate to API Keys section
  3. Click "Create New Key"
  4. Give your key a descriptive name
  5. Copy the generated key immediately

Key Permissions

API keys inherit the permissions of your account. You can:

  • Read match data
  • Access player statistics
  • Generate video clips
  • Use webhooks (if enabled)

Security Best Practices

  • Use different keys for different applications
  • Rotate keys regularly
  • Monitor key usage in your dashboard
  • Revoke compromised keys immediately

Error Responses

Authentication errors will return specific HTTP status codes:

Status Code Error Type Description
401 Unauthorized API key is missing or invalid
403 Forbidden API key doesn't have permission for this resource
429 Rate Limited Too many requests - check rate limits

Overview

MatchGraph API implements rate limiting to ensure fair usage and maintain service quality for all users. Rate limits are applied per API key and vary based on your subscription plan.

Rate Limit Windows

Rate limits are calculated over rolling time windows. For example, if you have 1000 requests per minute, you can make 1000 requests in any 60-second period, not just at the start of each minute.

Rate Limit Tiers

Different subscription plans have different rate limits:

Free Tier

Free
Requests per minute: 60
Requests per hour: 1,000
Requests per day: 10,000
  • Basic API access
  • Standard support
  • Community forums

Enterprise Tier

Custom
Requests per minute: 1,000+
Requests per hour: 50,000+
Requests per day: 500,000+
  • Custom rate limits
  • Dedicated support
  • SLA guarantees
  • Custom integrations

Rate Limit Headers

Every API response includes headers that provide information about your current rate limit status:

Response Headers
X-RateLimit-Limit: 300
X-RateLimit-Remaining: 299
X-RateLimit-Reset: 1640995200
X-RateLimit-Window: 60

X-RateLimit-Limit

The maximum number of requests allowed in the current time window.

X-RateLimit-Remaining

The number of requests remaining in the current time window.

X-RateLimit-Reset

The timestamp (in seconds) when the current rate limit window resets.

X-RateLimit-Window

The duration of the rate limit window in seconds.

Rate Limit Errors

When you exceed your rate limit, the API returns a 429 Too Many Requests error:

Rate Limit Error Response
{
  "error": {
    "code": "RATE_LIMIT_EXCEEDED",
    "message": "Rate limit exceeded. Try again in 45 seconds.",
    "retry_after": 45,
    "limit": 300,
    "remaining": 0,
    "reset": 1640995200
  }
}

retry_after

The number of seconds to wait before retrying your request.

limit

Your current rate limit for the time window.

remaining

How many requests you have remaining (0 when rate limited).

reset

The timestamp when your rate limit will reset.

Handling Rate Limits

Here are best practices for handling rate limits in your applications:

Exponential Backoff

Implement exponential backoff when you hit rate limits. Start with a 1-second delay and double it for each subsequent failure.

Exponential Backoff Example
async function makeRequestWithBackoff(url, maxRetries = 3) {
    let delay = 1000; // Start with 1 second
    
    for (let attempt = 0; attempt < maxRetries; attempt++) {
        try {
            const response = await fetch(url);
            
            if (response.status === 429) {
                const retryAfter = response.headers.get('Retry-After') || delay / 1000;
                console.log(`Rate limited. Waiting ${retryAfter} seconds...`);
                await new Promise(resolve => setTimeout(resolve, retryAfter * 1000));
                delay *= 2; // Exponential backoff
                continue;
            }
            
            return response;
        } catch (error) {
            if (attempt === maxRetries - 1) throw error;
            await new Promise(resolve => setTimeout(resolve, delay));
            delay *= 2;
        }
    }
}

Request Queuing

Queue requests and process them at a controlled rate to avoid hitting rate limits.

Request Queue Example
class RateLimitedQueue {
    constructor(requestsPerSecond = 5) {
        this.queue = [];
        this.processing = false;
        this.interval = 1000 / requestsPerSecond;
    }
    
    async add(requestFn) {
        return new Promise((resolve, reject) => {
            this.queue.push({ requestFn, resolve, reject });
            this.process();
        });
    }
    
    async process() {
        if (this.processing || this.queue.length === 0) return;
        
        this.processing = true;
        
        while (this.queue.length > 0) {
            const { requestFn, resolve, reject } = this.queue.shift();
            
            try {
                const result = await requestFn();
                resolve(result);
            } catch (error) {
                reject(error);
            }
            
            // Wait before processing next request
            await new Promise(resolve => setTimeout(resolve, this.interval));
        }
        
        this.processing = false;
    }
}

Monitor Usage

Track your API usage and implement alerts when approaching rate limits.

Usage Monitoring Example
function checkRateLimit(response) {
    const limit = parseInt(response.headers.get('X-RateLimit-Limit'));
    const remaining = parseInt(response.headers.get('X-RateLimit-Remaining'));
    const usagePercentage = ((limit - remaining) / limit) * 100;
    
    if (usagePercentage > 80) {
        console.warn(`High API usage: ${usagePercentage.toFixed(1)}%`);
        // Send alert to your monitoring system
    }
    
    return { limit, remaining, usagePercentage };
}

Best Practices

Cache Responses

Cache API responses to reduce the number of requests. Use appropriate cache headers and implement cache invalidation strategies.

Batch Requests

Use batch endpoints when available to reduce the number of individual API calls.

Respect Retry-After

Always respect the Retry-After header in rate limit responses to avoid overwhelming the API.

Monitor Usage

Implement monitoring to track your API usage and get alerts before hitting rate limits.

Use Multiple API Keys

For high-volume applications, consider using multiple API keys to distribute load.

Configure Timeouts

Set appropriate timeouts for your requests to avoid hanging connections.

Rate Limit by Endpoint

Different endpoints may have different rate limits based on their resource intensity:

Endpoint Rate Limit Notes
GET /players/* Standard Player data queries
GET /teams/* Standard Team statistics
GET /matches/* Standard Match data
POST /query Reduced Natural language queries (more intensive)
POST /graphql Reduced GraphQL queries
GET /matches/*/frames Reduced Frame data (high bandwidth)
POST /export/video Low Video generation (very intensive)

Upgrading Your Plan

If you're consistently hitting rate limits, consider upgrading your plan:

1

Monitor Your Usage

Check your API usage in the dashboard to understand your current consumption patterns.

2

Optimize Your Code

Implement caching, batching, and other optimizations to reduce API calls.

3

Contact Support

If you need custom rate limits or have specific requirements, contact our sales team.

Overview

The Natural Language API allows you to query MatchGraph data using everyday language. Simply describe what you want to know, and our AI will translate your request into the appropriate API calls.

AI-Powered Queries

Our natural language processing engine understands football terminology, player names, team references, and complex analytical requests. Just ask naturally!

Basic Usage

Send your query to the Natural Language endpoint:

Basic Request
curl -X POST "https://api.matchgraph.io/v1/query" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "query": "Show me all goals by player 9 in the last 5 matches",
    "format": "json"
  }'

Query Examples

Here are some examples of what you can ask:

Player Analysis

"Show me all goals and assists by player 9 in the last 5 matches"
Get comprehensive player performance data
"What is the shot accuracy for player 7 this season?"
Specific performance metrics
"Generate a player report for player 11 with focus on improvement areas"
AI-generated scouting reports
"Show me all sprints over 25 km/h by player 5"
Physical performance data

Team Analysis

"Show team stats for the last 5 matches including distance run and possession"
Team performance overview
"Compare possession stats between team A and team B"
Team comparisons
"Show heatmap for the entire team in the last match"
Visual analysis

Match Events

"Get frame by frame positions for the goal scored at 23:15 in match m127"
Detailed event analysis
"Show all through balls attempted in the second half"
Specific event types
"Generate a video clip of the penalty kick at 67:30"
Video export requests

Query Parameters

You can customize your natural language queries with additional parameters:

Parameter Type Required Description
query string Yes Your natural language query
format string No Response format: "json", "table", or "graph"
include_metadata boolean No Include query interpretation metadata
timezone string No Timezone for date/time values (e.g., "UTC", "Europe/London")
language string No Query language (default: "en")

Response Format

Natural Language API responses include the interpreted query and results:

Response Structure
{
  "query": {
    "original": "Show me all goals by player 9 in the last 5 matches",
    "interpreted": {
      "type": "player_events",
      "player_id": 9,
      "event_types": ["goal"],
      "match_count": 5,
      "time_range": "recent"
    },
    "confidence": 0.95
  },
  "results": {
    "events": [
      {
        "match_id": "m123",
        "timestamp": "2024-03-15T15:23:12",
        "type": "goal",
        "player_id": 9,
        "position": [32, 45],
        "details": {
          "assist_by": 11,
          "shot_type": "right_foot",
          "xG": 0.76
        }
      }
    ],
    "summary": {
      "total_events": 3,
      "matches_analyzed": 5,
      "time_period": "last_5_matches"
    }
  },
  "metadata": {
    "processing_time": 0.45,
    "api_calls_made": 2,
    "cache_hit": false
  }
}

Supported Query Types

The Natural Language API understands various types of football queries:

Player Queries

  • Performance statistics
  • Event analysis
  • Scouting reports
  • Physical metrics
  • Trend analysis

Team Queries

  • Team statistics
  • Formation analysis
  • Possession metrics
  • Team comparisons
  • Tactical insights

Match Queries

  • Match events
  • Timeline analysis
  • Key moments
  • Performance breakdowns
  • Video clips

Analytical Queries

  • Trend analysis
  • Comparative studies
  • Predictive insights
  • Statistical summaries
  • Custom metrics

Advanced Features

Query Suggestions

Get AI-powered suggestions to improve your queries for better results.

Query Improvement
{
  "query": "player 9 goals",
  "suggestions": [
    "Show me all goals by player 9 in the last 5 matches",
    "What is the goal scoring rate for player 9 this season?",
    "Compare goal scoring between player 9 and player 11"
  ]
}

Multi-language Support

Query in multiple languages including Spanish, French, German, and Portuguese.

Spanish Query
{
  "query": "Muéstrame todos los goles del jugador 9 en los últimos 5 partidos",
  "language": "es"
}

Video Generation

Request video clips directly through natural language queries.

Video Request
{
  "query": "Generate a video clip of the penalty kick at 67:30 in match m127",
  "format": "json"
}

Best Practices

Be Specific

Include specific details like player IDs, match IDs, time ranges, and event types for more accurate results.

Use Time References

Specify time periods like "last 5 matches", "this season", or "yesterday's match" for better context.

Combine Multiple Criteria

Combine different criteria in one query: "Show goals by player 9 in away matches this season".

Use Query Suggestions

Take advantage of AI suggestions to improve your queries and get better results.

Cache Results

Cache natural language query results to avoid repeated processing of similar requests.

Monitor Confidence

Check the confidence score in responses to ensure your query was interpreted correctly.

Error Handling

Common errors and how to handle them:

Low Confidence Queries

Low Confidence Response
{
  "error": {
    "code": "LOW_CONFIDENCE",
    "message": "Query interpretation confidence is low (0.3). Please rephrase your query.",
    "suggestions": [
      "Show me all goals by player 9",
      "What are the statistics for player 9?",
      "Get player 9's performance data"
    ]
  }
}

Ambiguous Queries

Ambiguous Query Response
{
  "error": {
    "code": "AMBIGUOUS_QUERY",
    "message": "Multiple interpretations possible. Please specify:",
    "clarifications": [
      "Which player do you mean? (player 9, player 19, etc.)",
      "Which match are you referring to?",
      "What time period do you want to analyze?"
    ]
  }
}

Rate Limits

Natural Language queries have different rate limits due to their computational complexity:

Free Tier

  • 10 queries per minute
  • 100 queries per hour
  • 1,000 queries per day

Pro Tier

  • 50 queries per minute
  • 500 queries per hour
  • 5,000 queries per day

Enterprise Tier

  • 200+ queries per minute
  • 2,000+ queries per hour
  • 20,000+ queries per day

Next Steps

Ready to start using the Natural Language API?

Overview

MatchGraph's GraphQL API provides a flexible, strongly-typed interface for querying football data. With GraphQL, you can request exactly the data you need, nothing more and nothing less.

Single Endpoint

All GraphQL operations go through a single endpoint: https://api.matchgraph.io/v1/graphql. No need to learn multiple REST endpoints.

Basic Usage

Send GraphQL queries to the GraphQL endpoint:

Basic GraphQL Request
curl -X POST "https://api.matchgraph.io/v1/graphql" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "query": "query PlayerStats { playerStats(playerId: \"9\") { matchesAnalyzed performanceMetrics { shooting { goals accuracy } } } }"
  }'

Schema Overview

The GraphQL schema is organized around these main types:

Queries

playerStats Player performance statistics
teamStats Team performance metrics
events Match events and actions
frameData Real-time position data
matches Match information and metadata

Mutations

exportVideo Generate video clips
createWebhook Set up webhook subscriptions
updatePreferences Update user preferences

Subscriptions

liveMatch Real-time match updates
playerEvents Live player event streams
teamMetrics Live team performance data

Query Examples

Here are practical examples of common GraphQL queries:

Player Statistics

Player Performance Query
query PlayerPerformance($playerId: ID!, $matchCount: Int) {
  playerStats(playerId: $playerId, matchCount: $matchCount) {
    matchesAnalyzed
    performanceMetrics {
      shooting {
        totalShots
        onTarget
        accuracy
        goals
        xG
      }
      passing {
        totalPasses
        completed
        completionRate
        throughBalls {
          attempted
          successful
          successRate
        }
      }
      physical {
        distanceCovered
        averageSpeed
        maxSpeed
        sprints
      }
    }
    teamComparison {
      shotAccuracy
      passCompletion
      distanceCovered
    }
  }
}

Team Analysis

Team Statistics Query
query TeamAnalysis($teamId: ID!, $matchCount: Int) {
  teamStats(teamId: $teamId, matchCount: $matchCount) {
    matchesAnalyzed
    overallMetrics {
      distanceRun {
        total
        averagePerMatch
        trend
      }
      intensity {
        acceleration {
          highIntensityCount
          averagePerMatch
        }
        deceleration {
          highIntensityCount
          averagePerMatch
        }
      }
      possession {
        averagePercentage
        ownHalf
        oppositionHalf
      }
    }
    matchBreakdown {
      matchId
      date
      metrics {
        distanceRun
        possessionPercentage
        highIntensityActions {
          total
          acceleration
          deceleration
        }
      }
    }
  }
}

Event Analysis

Match Events Query
query MatchEvents(
  $playerId: ID, 
  $matchIds: [ID!], 
  $eventType: [EventType!],
  $limit: Int
) {
  events(
    playerId: $playerId
    matchIds: $matchIds
    eventType: $eventType
    limit: $limit
  ) {
    matchId
    timestamp
    type
    playerId
    position
    details {
      assistBy
      shotType
      xG
      passType
      xA
    }
  }
}

Frame Data

Frame Data Query
query FrameAnalysis(
  $matchId: ID!, 
  $eventId: ID, 
  $timestamp: String, 
  $duration: Float
) {
  frameData(
    matchId: $matchId
    eventId: $eventId
    timestamp: $timestamp
    duration: $duration
  ) {
    eventDetails {
      eventType
      scorer
      assistBy
      period
    }
    frames {
      frameId
      timestamp
      ball {
        x
        y
        z
        velocity
      }
      players {
        teamA {
          playerId
          x
          y
          z
          orientation
          velocity
          acceleration
        }
        teamB {
          playerId
          x
          y
          z
          orientation
          velocity
          acceleration
        }
      }
      officials {
        role
        x
        y
        z
        orientation
      }
    }
    metadata {
      totalFrames
      frameRate
      durationSeconds
      calibrationConfidence
      trackingConfidence {
        players
        ball
        officials
      }
    }
  }
}

Mutations

GraphQL mutations allow you to modify data or trigger actions:

Video Export

Video Export Mutation
mutation ExportVideo($input: VideoExportInput!) {
  exportVideo(input: $input) {
    exportId
    status
    progress
    estimatedCompletion
    downloadUrl
    metadata {
      duration
      resolution
      format
      size
    }
  }
}
Variables
{
  "input": {
    "matchId": "m127",
    "eventId": "e456",
    "duration": 10.0,
    "format": "mp4",
    "resolution": "1080p",
    "annotations": {
      "showPlayerNames": true,
      "showTrajectories": true,
      "highlightEvent": true
    }
  }
}

Webhook Setup

Webhook Creation
mutation CreateWebhook($input: WebhookInput!) {
  createWebhook(input: $input) {
    webhookId
    url
    events
    status
    createdAt
    lastTriggered
  }
}

Subscriptions

Real-time data streaming with GraphQL subscriptions:

Live Match Updates

Live Match Subscription
subscription LiveMatch($matchId: ID!) {
  liveMatch(matchId: $matchId) {
    matchId
    timestamp
    period
    score {
      home
      away
    }
    events {
      type
      playerId
      timestamp
      position
    }
    metrics {
      possession {
        home
        away
      }
      shots {
        home
        away
      }
      distance {
        home
        away
      }
    }
  }
}

Player Event Stream

Player Events Subscription
subscription PlayerEvents($playerId: ID!, $eventTypes: [EventType!]) {
  playerEvents(playerId: $playerId, eventTypes: $eventTypes) {
    eventId
    matchId
    timestamp
    type
    position
    details {
      assistBy
      shotType
      xG
      passType
      xA
    }
    context {
      matchTime
      period
      score
    }
  }
}

Schema Types

Key GraphQL types and their fields:

PlayerStats

Type Definition
type PlayerStats {
  playerId: ID!
  matchesAnalyzed: Int!
  performanceMetrics: PerformanceMetrics!
  teamComparison: TeamComparison!
  trends: TrendAnalysis!
}

type PerformanceMetrics {
  shooting: ShootingMetrics!
  passing: PassingMetrics!
  physical: PhysicalMetrics!
  defensive: DefensiveMetrics!
}

type ShootingMetrics {
  totalShots: Int!
  onTarget: Int!
  accuracy: Float!
  goals: Int!
  xG: Float!
  shotTypes: [ShotType!]!
}

type PassingMetrics {
  totalPasses: Int!
  completed: Int!
  completionRate: Float!
  throughBalls: ThroughBallMetrics!
  keyPasses: Int!
  assists: Int!
  xA: Float!
}

Event

Type Definition
type Event {
  eventId: ID!
  matchId: ID!
  timestamp: String!
  type: EventType!
  playerId: ID
  position: Position!
  details: EventDetails!
  context: EventContext!
}

type Position {
  x: Float!
  y: Float!
  z: Float
}

type EventDetails {
  assistBy: ID
  shotType: ShotType
  xG: Float
  passType: PassType
  xA: Float
  tackleType: TackleType
  foulType: FoulType
}

enum EventType {
  GOAL
  ASSIST
  SHOT
  PASS
  TACKLE
  INTERCEPTION
  FOUL
  SPRINT
  SUBSTITUTION
}

Best Practices

Request Only What You Need

GraphQL's power comes from requesting exactly the fields you need. Avoid over-fetching data.

Use Fragments

Create reusable fragments for common field selections to keep queries DRY.

Use Variables

Always use variables for dynamic values to prevent injection attacks and improve caching.

Monitor Query Complexity

Complex queries can impact performance. Use the query complexity analysis to optimize.

Implement Caching

Use GraphQL-specific caching strategies to improve performance and reduce API calls.

Handle Errors Gracefully

GraphQL returns partial data on errors. Always check the errors field in responses.

Error Handling

GraphQL provides structured error handling:

Error Response
{
  "data": {
    "playerStats": null
  },
  "errors": [
    {
      "message": "Player not found",
      "locations": [
        {
          "line": 2,
          "column": 3
        }
      ],
      "path": ["playerStats"],
      "extensions": {
        "code": "PLAYER_NOT_FOUND",
        "playerId": "999"
      }
    }
  ]
}

Rate Limits

GraphQL queries have the same rate limits as other API endpoints, but with additional complexity limits:

Query Complexity

  • Free Tier: 100 points per query
  • Pro Tier: 500 points per query
  • Enterprise Tier: 1000+ points per query

Depth Limits

  • Maximum nesting depth: 10 levels
  • Maximum array size: 1000 items
  • Maximum query length: 50,000 characters

Next Steps

Ready to explore the GraphQL API?

Overview

The MatchGraph REST API provides a familiar HTTP-based interface for accessing football data. All endpoints return JSON responses and follow RESTful conventions.

Base URL

All API requests should be made to: https://api.matchgraph.io/v1

Authentication

All REST API requests require authentication using your API key in the Authorization header:

Authentication Header
Authorization: Bearer YOUR_API_KEY

Endpoints Overview

The REST API is organized into the following resource categories:

Players

GET /players/{playerId}/stats Player performance statistics
GET /players/{playerId}/profile Player profile and attributes
GET /players/{playerId}/events Player match events

Teams

GET /teams/{teamId}/stats Team performance statistics
GET /teams/{teamId}/players Team roster and player list
GET /teams/{teamId}/matches Team match history

Matches

GET /matches/{matchId} Match information and metadata
GET /matches/{matchId}/events Match events and timeline
GET /matches/{matchId}/frames Real-time position data

Events

GET /events Filtered event queries
GET /events/{eventId} Specific event details

Player Endpoints

Access player statistics, profiles, and performance data:

GET /players/{playerId}/stats

Retrieve comprehensive player performance statistics for a specified time period.

Parameter Type Required Description
playerId string Yes Unique player identifier
matchCount integer No Number of recent matches to analyze (default: 5)
startDate string No Start date in ISO 8601 format
endDate string No End date in ISO 8601 format
Example Request
curl -X GET "https://api.matchgraph.io/v1/players/9/stats?matchCount=10" \
  -H "Authorization: Bearer YOUR_API_KEY"
Example Response
{
  "player_id": "9",
  "matches_analyzed": 10,
  "performance_metrics": {
    "shooting": {
      "total_shots": 25,
      "on_target": 15,
      "accuracy": 60.0,
      "goals": 8,
      "xG": 6.2
    },
    "passing": {
      "total_passes": 450,
      "completed": 380,
      "completion_rate": 84.4,
      "through_balls": {
        "attempted": 18,
        "successful": 12,
        "success_rate": 66.7
      }
    },
    "physical": {
      "distance_covered": 95.2,
      "average_speed": 7.8,
      "max_speed": 32.5,
      "sprints": 45
    }
  },
  "team_comparison": {
    "shot_accuracy": "+12.5%",
    "pass_completion": "+5.3%",
    "distance_covered": "+8.2%"
  }
}

GET /players/{playerId}/profile

Get detailed player profile information including attributes and scouting data.

Example Request
curl -X GET "https://api.matchgraph.io/v1/players/9/profile" \
  -H "Authorization: Bearer YOUR_API_KEY"
Example Response
{
  "player_id": "9",
  "name": "Player 9",
  "position": "Forward",
  "key_attributes": {
    "speed": {
      "rating": 85,
      "trend": "+3",
      "details": {
        "sprint_speed": 32.5,
        "acceleration": 88
      }
    },
    "technical": {
      "rating": 79,
      "trend": "+2",
      "details": {
        "ball_control": 76,
        "passing": 81
      }
    }
  },
  "scout_notes": {
    "strengths": ["Explosive acceleration", "Excellent finishing", "Good vision"],
    "areas_for_improvement": ["Defensive positioning", "Aerial duels"]
  }
}

Team Endpoints

Access team statistics and performance data:

GET /teams/{teamId}/stats

Retrieve comprehensive team performance statistics and metrics.

Parameter Type Required Description
teamId string Yes Unique team identifier
matchCount integer No Number of recent matches to analyze (default: 5)
season string No Season identifier (e.g., "2023-24")
Example Request
curl -X GET "https://api.matchgraph.io/v1/teams/team_a/stats?matchCount=10" \
  -H "Authorization: Bearer YOUR_API_KEY"
Example Response
{
  "team_id": "team_a",
  "matches_analyzed": 10,
  "overall_metrics": {
    "distance_run": {
      "total": 1052.3,
      "average_per_match": 105.23,
      "trend": "+3.2%"
    },
    "intensity": {
      "acceleration": {
        "high_intensity_count": 490,
        "average_per_match": 49
      },
      "deceleration": {
        "high_intensity_count": 396,
        "average_per_match": 39.6
      }
    },
    "possession": {
      "average_percentage": 58.4,
      "own_half": 35.2,
      "opposition_half": 64.8
    }
  },
  "match_breakdown": [
    {
      "match_id": "m127",
      "date": "2024-03-20",
      "metrics": {
        "distance_run": 107.2,
        "possession_percentage": 62.5,
        "high_intensity_actions": {
          "total": 52,
          "acceleration": 31,
          "deceleration": 21
        }
      }
    }
  ]
}

Match Endpoints

Access match data, events, and real-time position information:

GET /matches/{matchId}/events

Retrieve all events that occurred during a specific match.

Parameter Type Required Description
matchId string Yes Unique match identifier
eventType string No Filter by event type (GOAL, ASSIST, SHOT, etc.)
playerId string No Filter by specific player
period integer No Match period (1 or 2)
Example Request
curl -X GET "https://api.matchgraph.io/v1/matches/m127/events?eventType=GOAL&playerId=9" \
  -H "Authorization: Bearer YOUR_API_KEY"
Example Response
{
  "match_id": "m127",
  "events": [
    {
      "event_id": "e456",
      "timestamp": "2024-03-20T15:23:12",
      "type": "GOAL",
      "player_id": "9",
      "position": {
        "x": 32.5,
        "y": 45.2
      },
      "details": {
        "assist_by": "11",
        "shot_type": "right_foot",
        "xG": 0.76
      },
      "context": {
        "match_time": "23:15",
        "period": 1,
        "score": {
          "home": 1,
          "away": 0
        }
      }
    }
  ],
  "total_events": 1,
  "filters_applied": {
    "eventType": "GOAL",
    "playerId": "9"
  }
}

GET /matches/{matchId}/frames

Retrieve real-time position data for players, ball, and officials during a match.

Parameter Type Required Description
matchId string Yes Unique match identifier
eventId string No Event ID to get frames for (if provided, timestamp becomes optional)
timestamp string No Specific timestamp (required if eventId not provided)
duration float No Duration in seconds (default: 10.0)
Example Request
curl -X GET "https://api.matchgraph.io/v1/matches/m127/frames?eventId=e456&duration=15.0" \
  -H "Authorization: Bearer YOUR_API_KEY"

Event Endpoints

Query and filter events across multiple matches:

GET /events

Search and filter events across multiple matches with various criteria.

Parameter Type Required Description
playerId string No Filter by specific player
matchIds string No Comma-separated list of match IDs
eventType string No Comma-separated list of event types
startTime string No Start time in ISO 8601 format
endTime string No End time in ISO 8601 format
limit integer No Maximum number of events to return (default: 100)
offset integer No Number of events to skip for pagination
Example Request
curl -X GET "https://api.matchgraph.io/v1/events?playerId=9&eventType=GOAL,ASSIST&limit=10" \
  -H "Authorization: Bearer YOUR_API_KEY"
Example Response
{
  "events": [
    {
      "event_id": "e456",
      "match_id": "m127",
      "timestamp": "2024-03-20T15:23:12",
      "type": "GOAL",
      "player_id": "9",
      "position": {
        "x": 32.5,
        "y": 45.2
      },
      "details": {
        "assist_by": "11",
        "shot_type": "right_foot",
        "xG": 0.76
      }
    },
    {
      "event_id": "e457",
      "match_id": "m125",
      "timestamp": "2024-03-18T14:15:30",
      "type": "ASSIST",
      "player_id": "9",
      "position": {
        "x": 28.1,
        "y": 40.3
      },
      "details": {
        "scored_by": "7",
        "pass_type": "through_ball",
        "xA": 0.45
      }
    }
  ],
  "total_events": 2,
  "filters_applied": {
    "playerId": "9",
    "eventType": "GOAL,ASSIST"
  },
  "pagination": {
    "limit": 10,
    "offset": 0,
    "has_more": false
  }
}

Error Handling

REST API errors follow standard HTTP status codes and include detailed error information:

400 Bad Request

Invalid Parameters
{
  "error": {
    "code": "INVALID_PARAMETER",
    "message": "Invalid matchCount parameter. Must be between 1 and 50.",
    "parameter": "matchCount",
    "value": "100"
  }
}

404 Not Found

Resource Not Found
{
  "error": {
    "code": "PLAYER_NOT_FOUND",
    "message": "Player with ID '999' not found.",
    "player_id": "999"
  }
}

429 Too Many Requests

Rate Limit Exceeded
{
  "error": {
    "code": "RATE_LIMIT_EXCEEDED",
    "message": "Rate limit exceeded. Try again in 45 seconds.",
    "retry_after": 45,
    "limit": 300,
    "remaining": 0,
    "reset": 1640995200
  }
}

Rate Limits

REST API endpoints follow the same rate limiting as other API interfaces:

Standard Endpoints

  • GET /players/* - Standard limits
  • GET /teams/* - Standard limits
  • GET /matches/* - Standard limits
  • GET /events - Standard limits

High-Bandwidth Endpoints

  • GET /matches/*/frames - Reduced limits
  • POST /export/video - Low limits

Best Practices

Use Caching

Cache responses using appropriate cache headers to reduce API calls and improve performance.

Use Filters

Always use query parameters to filter data and reduce response size.

Implement Pagination

Use limit and offset parameters for large datasets to avoid timeouts.

Monitor Rate Limits

Check rate limit headers in responses to avoid hitting limits.

Secure API Keys

Never expose API keys in client-side code or public repositories.

Handle Errors Gracefully

Implement proper error handling and retry logic for failed requests.

Next Steps

Ready to start using the REST API?

Event Types

Content coming soon...

Player Attributes

Content coming soon...

Team Statistics

Content coming soon...

Match Information

Content coming soon...

Frame Structure

Content coming soon...

Common Queries

Content coming soon...

Video Generation

Content coming soon...

Webhook Setup

Content coming soon...

Available SDKs

Content coming soon...

Error Codes

Content coming soon...

API Best Practices

Content coming soon...

Common Issues

Content coming soon...