import osimport requestsimport timeDEVIN_API_KEY = os.getenv("DEVIN_API_KEY")# Create a new sessionresponse = 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 statuswhile 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)
File Upload and Processing
import osimport requestsDEVIN_API_KEY = os.getenv("DEVIN_API_KEY")# Upload a filewith 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 fileresponse = 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()))
Interactive Sessions
import osimport requestsDEVIN_API_KEY = os.getenv("DEVIN_API_KEY")# Send a message to an active sessionrequests.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." })
Using Session Secrets
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 osimport requestsDEVIN_API_KEY = os.getenv("DEVIN_API_KEY")# Create a session with session-specific secretsresponse = 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
GitHub Repository Analysis
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 osimport aiohttpimport asynciofrom typing import List, DictAPI_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 *= 2async 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())