Skip to main content
This page provides code examples for common v1 API use cases.

Quick Examples

import os
import requests
import time

DEVIN_API_KEY = os.getenv("DEVIN_API_KEY")

# Create a new session
response = requests.post(
    "https://api.devin.ai/v1/sessions",
    headers={"Authorization": f"Bearer {DEVIN_API_KEY}"},
    json={
        "prompt": "Review PR #249",
        "idempotent": True
    }
)

print("Response:\n"+ str(response.json()))
session_id = response.json()["session_id"]

# Monitor session status
while True:
    status = requests.get(
        f"https://api.devin.ai/v1/sessions/{session_id}",
        headers={"Authorization": f"Bearer {DEVIN_API_KEY}"}
    ).json()
    print("Status:\n" + str(status))
    if status["status_enum"] in ["blocked", "finished"]:
        break
    time.sleep(5)
import os
import requests

DEVIN_API_KEY = os.getenv("DEVIN_API_KEY")

# Upload a file
with open("data.csv", "rb") as f:
    response = requests.post(
        "https://api.devin.ai/v1/attachments",
        headers={"Authorization": f"Bearer {DEVIN_API_KEY}"},
        files={"file": f}
    )
file_url = response.text

# Create a session to process the file
response = requests.post(
    "https://api.devin.ai/v1/sessions",
    headers={"Authorization": f"Bearer {DEVIN_API_KEY}"},
    json={
        "prompt": f"Analyze the data in the attached file.\n\nATTACHMENT:\"{file_url}\""
    }
)

print(str(response.json()))
import os
import requests

DEVIN_API_KEY = os.getenv("DEVIN_API_KEY")

# Send a message to an active session
requests.post(
    f"https://api.devin.ai/v1/sessions/{session_id}/message",
    headers={"Authorization": f"Bearer {DEVIN_API_KEY}"},
    json={
        "message": "Make sure to write units tests when you are done."
    }
)
Session secrets allow you to provide temporary credentials or API keys that are only available for a single session and are not stored in your organization’s secrets.
import os
import requests

DEVIN_API_KEY = os.getenv("DEVIN_API_KEY")

# Create a session with session-specific secrets
response = requests.post(
    "https://api.devin.ai/v1/sessions",
    headers={"Authorization": f"Bearer {DEVIN_API_KEY}"},
    json={
        "prompt": "Deploy the application to the staging environment",
        "session_secrets": [
            {
                "key": "DEPLOY_API_KEY",
                "value": "your-temporary-deploy-key",
                "sensitive": True
            },
            {
                "key": "STAGING_URL",
                "value": "https://staging.example.com",
                "sensitive": False
            }
        ]
    }
)

print(response.json())
Notes:
  • Secret keys must follow environment variable naming conventions (start with a letter or underscore, followed by letters, numbers, or underscores)
  • The sensitive field defaults to true if not specified
  • Session secrets are only available in the session they are created with and are not stored in organization secrets
Here’s a complete example that demonstrates how to use the Devin API to analyze GitHub repositories. This example shows:
  • Authentication and error handling
  • Creating and monitoring sessions
  • Processing structured output
  • Proper resource management with async/await
import os
import aiohttp
import asyncio
from typing import List, Dict

API_KEY = os.getenv("DEVIN_API_KEY")
API_BASE = "https://api.devin.ai/v1"

async def count_stars(session: aiohttp.ClientSession, repo_url: str) -> int:
    """Count stars for a GitHub repository using Devin."""
    # Create a new Devin session
    async with session.post(
        f"{API_BASE}/sessions",
        json={"prompt": f"Count stars for GitHub repository: {repo_url}"}
    ) as response:
        session_data = await response.json()
        session_id = session_data["session_id"]
        print(f"Created session {session_id} for {repo_url}")
        print(f"URL: {session_data['url']}")

    # Poll for results with exponential backoff
    backoff = 1
    print("Polling for results...")
    while True:
        async with session.get(
            f"{API_BASE}/sessions/{session_id}"
        ) as response:
            response_json = await response.json()
            if response_json["status_enum"] in ["blocked", "finished"]:
                return response_json["structured_output"].get("star_count", 0)
        await asyncio.sleep(min(backoff, 30))
        backoff *= 2

async def main():
    """Main function to analyze GitHub repositories."""
    headers = {"Authorization": f"Bearer {API_KEY}"}
    async with aiohttp.ClientSession(headers=headers) as session:
        # Example repositories to analyze
        repos = [
            "https://github.com/openai/openai-python",
            "https://github.com/anthropics/anthropic-sdk-python"
        ]
        
        # Count stars for each repository
        for repo in repos:
            stars = await count_stars(session, repo)
            print(f"{repo}: {stars} stars")

if __name__ == "__main__":
    asyncio.run(main())

Advanced Examples

Automated QA Testing

See how we use Devin to QA test Devin itself. Automate end-to-end testing using Devin’s browser capabilities.

Automated PR Reviews

Learn how to integrate Devin with GitHub Actions for automated PR reviews.

Support

Need Help?

For questions about the API or to report issues, email support@cognition.ai