API ReferenceAPI Overview

Mesrai API Overview

The Mesrai API allows you to programmatically interact with Mesrai’s code review platform. Build custom integrations, automate workflows, and extend Mesrai’s capabilities.

Base URL

All API requests should be made to:

https://api.mesrai.com/v1

Authentication

Mesrai API uses API keys for authentication. Include your API key in the Authorization header:

curl https://api.mesrai.com/v1/reviews \
  -H "Authorization: Bearer msr_live_abc123..."

Get your API key from the Mesrai Dashboard under Settings → API Keys.

Creating an API Key

Go to Dashboard Settings

Generate New Key

Click “Create API Key”

Configure Permissions

Select the scopes your key needs:

  • review:read - Read review data
  • review:write - Create and update reviews
  • org:read - Read organization data
  • org:write - Manage organizations
  • team:read - Read team data
  • team:write - Manage teams

Save Securely

Copy and store your API key securely. You won’t be able to see it again!

API Versioning

The Mesrai API is versioned. The current version is v1. The version is included in the URL path:

https://api.mesrai.com/v1/...

We maintain backward compatibility within major versions. Breaking changes will result in a new major version.

Request Format

Headers

All requests should include:

Content-Type: application/json
Authorization: Bearer msr_live_abc123...
X-Mesrai-Version: 2025-01-01

Request Body

POST and PUT requests should include a JSON body:

{
  "pull_request_url": "https://github.com/owner/repo/pull/123",
  "auto_review": true
}

Response Format

All responses are returned in JSON format with this structure:

Successful Response

{
  "data": {
    "id": "rev_abc123",
    "status": "completed",
    "score": 92
  },
  "meta": {
    "request_id": "req_xyz789",
    "timestamp": "2025-01-15T10:30:00Z"
  }
}

Error Response

{
  "error": {
    "type": "validation_error",
    "message": "Invalid pull request URL",
    "code": "invalid_pr_url",
    "status": 400,
    "details": {
      "field": "pull_request_url",
      "issue": "URL format is invalid"
    }
  },
  "meta": {
    "request_id": "req_xyz789",
    "timestamp": "2025-01-15T10:30:00Z"
  }
}

HTTP Status Codes

Status CodeDescription
200 OKRequest successful
201 CreatedResource created successfully
204 No ContentRequest successful, no content returned
400 Bad RequestInvalid request parameters
401 UnauthorizedMissing or invalid API key
403 ForbiddenInsufficient permissions
404 Not FoundResource not found
422 Unprocessable EntityValidation failed
429 Too Many RequestsRate limit exceeded
500 Internal Server ErrorServer error
503 Service UnavailableService temporarily unavailable

Error Codes

Common error codes you might encounter:

CodeDescription
invalid_api_keyAPI key is invalid or expired
insufficient_permissionsAPI key lacks required scopes
rate_limit_exceededYou’ve exceeded your rate limit
invalid_requestRequest format is invalid
validation_errorRequest validation failed
resource_not_foundRequested resource doesn’t exist
conflictResource conflict (e.g., duplicate)
internal_errorInternal server error

Rate Limiting

API requests are rate limited based on your plan:

PlanRate Limit
Free100 requests/hour
Pro1,000 requests/hour
Enterprise10,000 requests/hour

Rate limit information is included in response headers:

X-RateLimit-Limit: 1000
X-RateLimit-Remaining: 999
X-RateLimit-Reset: 1642377600
⚠️

When you exceed your rate limit, you’ll receive a 429 Too Many Requests response. Wait until the reset time before making more requests.

Pagination

List endpoints support pagination using cursor-based pagination:

Request

curl "https://api.mesrai.com/v1/reviews?limit=25&after=rev_abc123" \
  -H "Authorization: Bearer msr_live_..."

Response

{
  "data": [
    { "id": "rev_def456", ... },
    { "id": "rev_ghi789", ... }
  ],
  "pagination": {
    "has_more": true,
    "next_cursor": "rev_ghi789"
  }
}

Parameters

  • limit (optional): Number of items per page (default: 25, max: 100)
  • after (optional): Cursor for next page
  • before (optional): Cursor for previous page

Filtering and Sorting

Many list endpoints support filtering and sorting:

# Filter by status and sort by created date
curl "https://api.mesrai.com/v1/reviews?status=completed&sort=-created_at" \
  -H "Authorization: Bearer msr_live_..."

Common Query Parameters

  • status: Filter by status
  • created_after: Filter by creation date
  • created_before: Filter by creation date
  • sort: Sort results (prefix with - for descending)

Idempotency

POST requests support idempotency to safely retry requests:

curl -X POST https://api.mesrai.com/v1/reviews \
  -H "Authorization: Bearer msr_live_..." \
  -H "Idempotency-Key: unique-key-123" \
  -d '{"pull_request_url": "..."}'

If you retry a request with the same Idempotency-Key within 24 hours, you’ll receive the same response as the original request.

Webhooks

Subscribe to real-time events via webhooks. See Webhooks API for details.

SDK Libraries

Official SDKs are available for popular languages:

npm install @mesrai/sdk
import { Mesrai } from '@mesrai/sdk'
 
const mesrai = new Mesrai({
  apiKey: 'msr_live_...'
})
 
const review = await mesrai.reviews.create({
  pullRequestUrl: 'https://github.com/owner/repo/pull/123'
})

Testing

Use the test API key for development:

msr_test_abc123...

Test mode features:

  • No charges applied
  • Use test data
  • Predictable responses
  • No side effects

Test API keys are prefixed with msr_test_ while live keys use msr_live_.

Best Practices

1. Store API Keys Securely

# Use environment variables
export MESRAI_API_KEY="msr_live_..."
 
# Never commit API keys to version control
echo "MESRAI_API_KEY=msr_live_..." >> .env
echo ".env" >> .gitignore

2. Handle Errors Gracefully

try {
  const review = await mesrai.reviews.create(params)
} catch (error) {
  if (error.status === 429) {
    // Rate limit exceeded - wait and retry
    await sleep(error.retryAfter * 1000)
    return retry()
  }
 
  if (error.status >= 500) {
    // Server error - log and alert
    logger.error('Mesrai API error', error)
    alertOncall()
  }
 
  // Handle other errors
  throw error
}

3. Use Idempotency Keys

const idempotencyKey = generateUUID()
 
const review = await mesrai.reviews.create({
  pullRequestUrl: prUrl,
  idempotencyKey
})

4. Implement Exponential Backoff

async function retryWithBackoff(fn, maxRetries = 3) {
  for (let i = 0; i < maxRetries; i++) {
    try {
      return await fn()
    } catch (error) {
      if (i === maxRetries - 1) throw error
 
      const delay = Math.pow(2, i) * 1000
      await sleep(delay)
    }
  }
}

5. Monitor API Usage

Track your API usage and set up alerts:

const usage = await mesrai.account.usage()
 
if (usage.rate_limit.remaining < 100) {
  alert('Low API quota remaining')
}

Support and Resources

Documentation

Help

Changelog

Stay updated with API changes:

Quick Start Example

Here’s a complete example to get started:

import { Mesrai } from '@mesrai/sdk'
 
const mesrai = new Mesrai({
  apiKey: process.env.MESRAI_API_KEY
})
 
// Create a review
const review = await mesrai.reviews.create({
  pullRequestUrl: 'https://github.com/owner/repo/pull/123',
  autoReview: true
})
 
console.log(`Review created: ${review.id}`)
console.log(`Status: ${review.status}`)
console.log(`Score: ${review.score}`)
 
// Wait for completion
while (review.status !== 'completed') {
  await new Promise(resolve => setTimeout(resolve, 1000))
  review = await mesrai.reviews.retrieve(review.id)
}
 
// Get review comments
const comments = await mesrai.reviews.comments.list(review.id)
console.log(`Found ${comments.data.length} issues`)

Ready to build with Mesrai? Get your API key →