Integration Examples

Real-world examples of integrating the Coding Evaluation API into your applications.

Ready-to-Use Examples

These examples demonstrate common integration patterns and best practices. Copy and modify them to fit your specific use case. Each example includes error handling, authentication, and proper API usage.

JavaScript/Node.js Integration

Complete example of integrating the API in a Node.js application

1const axios = require('axios');
2 
3class CodingEvaluationAPI {
4 constructor(apiKey, baseUrl = 'https://evaluation.interviewscreener.com/api') {
5 this.apiKey = apiKey;
6 this.baseUrl = baseUrl;
7 this.headers = {
8 'Authorization': `Bearer ${apiKey}`,
9 'Content-Type': 'application/json'
10 };
11 }
12 
13 // Create a new test
14 async createTest(testData) {
15 try {
16 const response = await axios.post(`${this.baseUrl}/tests`, testData, {
17 headers: this.headers
18 });
19 return response.data;
20 } catch (error) {
21 throw new Error(`Failed to create test: ${error.message}`);
22 }
23 }
24 
25 // Get candidate submissions
26 async getSubmissions(filters = {}) {
27 try {
28 const params = new URLSearchParams(filters);
29 const response = await axios.get(`${this.baseUrl}/submissions?${params}`, {
30 headers: this.headers
31 });
32 return response.data;
33 } catch (error) {
34 throw new Error(`Failed to get submissions: ${error.message}`);
35 }
36 }
37 
38 // Run code execution
39 async runCode(code, language, questionId) {
40 try {
41 const response = await axios.post(`${this.baseUrl}/submissions/run`, {
42 code,
43 language,
44 questionId
45 }, {
46 headers: this.headers
47 });
48 return response.data;
49 } catch (error) {
50 throw new Error(`Failed to run code: ${error.message}`);
51 }
52 }
53}
54 
55// Usage Example
56const api = new CodingEvaluationAPI('your-jwt-token');
57 
58async function createCodingTest() {
59 const testData = {
60 title: "Senior Developer Assessment",
61 description: "Comprehensive coding test for senior positions",
62 duration: 120, // 2 hours
63 questions: [
64 {
65 type: "coding",
66 questionId: "two-sum-problem",
67 points: 25
68 },
69 {
70 type: "mcq",
71 questionId: "javascript-concepts",
72 points: 10
73 }
74 ],
75 proctoring: {
76 allowCopyPaste: false,
77 allowTabSwitch: false,
78 maxTabSwitches: 3
79 }
80 };
81 
82 try {
83 const result = await api.createTest(testData);
84 console.log('Test created:', result);
85 return result;
86 } catch (error) {
87 console.error('Error:', error.message);
88 }
89}
90 
91createCodingTest();

Python Integration

Python example using requests library

1import requests
2import json
3from typing import Dict, Any, Optional
4 
5class CodingEvaluationAPI:
6 def __init__(self, api_key: str, base_url: str = "https://evaluation.interviewscreener.com/api"):
7 self.api_key = api_key
8 self.base_url = base_url
9 self.headers = {
10 "Authorization": f"Bearer {api_key}",
11 "Content-Type": "application/json"
12 }
13
14 def create_question(self, question_data: Dict[str, Any]) -> Dict[str, Any]:
15 """Create a new coding question"""
16 try:
17 response = requests.post(
18 f"{self.base_url}/questions",
19 json=question_data,
20 headers=self.headers
21 )
22 response.raise_for_status()
23 return response.json()
24 except requests.exceptions.RequestException as e:
25 raise Exception(f"Failed to create question: {e}")
26
27 def get_test_results(self, test_id: str) -> Dict[str, Any]:
28 """Get comprehensive test results"""
29 try:
30 response = requests.get(
31 f"{self.base_url}/tests/{test_id}/results",
32 headers=self.headers
33 )
34 response.raise_for_status()
35 return response.json()
36 except requests.exceptions.RequestException as e:
37 raise Exception(f"Failed to get test results: {e}")
38
39 def evaluate_submission(self, submission_id: str) -> Dict[str, Any]:
40 """Get detailed submission evaluation"""
41 try:
42 response = requests.get(
43 f"{self.base_url}/submissions/{submission_id}/evaluation",
44 headers=self.headers
45 )
46 response.raise_for_status()
47 return response.json()
48 except requests.exceptions.RequestException as e:
49 raise Exception(f"Failed to get evaluation: {e}")
50 
51# Usage Example
52api = CodingEvaluationAPI("your-jwt-token")
53 
54# Create a coding question
55question_data = {
56 "type": "coding",
57 "title": "Binary Tree Traversal",
58 "description": "Implement in-order traversal of a binary tree",
59 "difficulty": "medium",
60 "category": "trees",
61 "topic": "Binary Trees",
62 "subtopic": "Tree Traversal",
63 "marks": 30,
64 "timeLimit": 600, # 10 minutes
65 "memoryLimit": 512,
66 "boilerplateCode": {
67 "python": "def inorder_traversal(root):\n pass",
68 "javascript": "function inorderTraversal(root) {\n // Your code here\n}"
69 },
70 "testCases": [
71 {
72 "id": "tc_1",
73 "input": "[1,null,2,3]",
74 "expectedOutput": "[1,3,2]",
75 "isHidden": False,
76 "description": "Basic test case"
77 }
78 ]
79}
80 
81try:
82 result = api.create_question(question_data)
83 print("Question created:", result)
84except Exception as e:
85 print("Error:", e)

React Frontend Integration

React component for test-taking interface

1import React, { useState, useEffect } from 'react';
2import axios from 'axios';
3 
4const CodingTest = ({ testId, candidateToken }) => {
5 const [test, setTest] = useState(null);
6 const [currentQuestion, setCurrentQuestion] = useState(0);
7 const [answers, setAnswers] = useState({});
8 const [timeRemaining, setTimeRemaining] = useState(0);
9 const [isSubmitting, setIsSubmitting] = useState(false);
10 
11 const API_BASE = 'https://evaluation.interviewscreener.com/api';
12
13 const headers = {
14 'Authorization': `Bearer ${candidateToken}`,
15 'Content-Type': 'application/json'
16 };
17 
18 useEffect(() => {
19 fetchTest();
20 }, [testId]);
21 
22 useEffect(() => {
23 if (timeRemaining > 0) {
24 const timer = setTimeout(() => {
25 setTimeRemaining(timeRemaining - 1);
26 }, 1000);
27 return () => clearTimeout(timer);
28 } else if (timeRemaining === 0 && test) {
29 handleSubmitTest();
30 }
31 }, [timeRemaining]);
32 
33 const fetchTest = async () => {
34 try {
35 const response = await axios.get(`${API_BASE}/tests/${testId}`, { headers });
36 setTest(response.data.data);
37 setTimeRemaining(response.data.data.duration * 60); // Convert minutes to seconds
38 } catch (error) {
39 console.error('Failed to fetch test:', error);
40 }
41 };
42 
43 const runCode = async (code, language, questionId) => {
44 try {
45 const response = await axios.post(`${API_BASE}/submissions/run`, {
46 code,
47 language,
48 questionId
49 }, { headers });
50 return response.data;
51 } catch (error) {
52 console.error('Failed to run code:', error);
53 return null;
54 }
55 };
56 
57 const handleAnswerChange = (questionId, answer) => {
58 setAnswers(prev => ({
59 ...prev,
60 [questionId]: answer
61 }));
62 };
63 
64 const handleSubmitTest = async () => {
65 setIsSubmitting(true);
66 try {
67 const submission = {
68 testId,
69 answers,
70 timeSpent: (test.duration * 60) - timeRemaining,
71 status: 'completed'
72 };
73 
74 const response = await axios.post(`${API_BASE}/submissions`, submission, { headers });
75 console.log('Test submitted successfully:', response.data);
76
77 // Redirect to completion page
78 window.location.href = '/test-completed';
79 } catch (error) {
80 console.error('Failed to submit test:', error);
81 } finally {
82 setIsSubmitting(false);
83 }
84 };
85 
86 const formatTime = (seconds) => {
87 const hours = Math.floor(seconds / 3600);
88 const minutes = Math.floor((seconds % 3600) / 60);
89 const secs = seconds % 60;
90 return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
91 };
92 
93 if (!test) {
94 return <div className="loading">Loading test...</div>;
95 }
96 
97 const question = test.questions[currentQuestion];
98 
99 return (
100 <div className="coding-test-container">
101 <header className="test-header">
102 <h1>{test.title}</h1>
103 <div className="test-info">
104 <span>Question {currentQuestion + 1} of {test.questions.length}</span>
105 <span className="time-remaining">Time: {formatTime(timeRemaining)}</span>
106 </div>
107 </header>
108 
109 <main className="test-content">
110 <div className="question-panel">
111 <h2>{question.title}</h2>
112 <div className="question-description">
113 {question.description}
114 </div>
115
116 {question.type === 'coding' && (
117 <div className="coding-interface">
118 <textarea
119 value={answers[question.id] || question.boilerplateCode?.javascript || ''}
120 onChange={(e) => handleAnswerChange(question.id, e.target.value)}
121 placeholder="Write your code here..."
122 className="code-editor"
123 />
124 <button
125 onClick={() => runCode(answers[question.id], 'javascript', question.id)}
126 className="run-code-btn"
127 >
128 Run Code
129 </button>
130 </div>
131 )}
132 
133 {question.type === 'mcq' && (
134 <div className="mcq-options">
135 {question.options.map(option => (
136 <label key={option.id} className="option-label">
137 <input
138 type="radio"
139 name={question.id}
140 value={option.id}
141 onChange={(e) => handleAnswerChange(question.id, e.target.value)}
142 />
143 {option.text}
144 </label>
145 ))}
146 </div>
147 )}
148 </div>
149 
150 <div className="navigation">
151 <button
152 onClick={() => setCurrentQuestion(Math.max(0, currentQuestion - 1))}
153 disabled={currentQuestion === 0}
154 >
155 Previous
156 </button>
157
158 {currentQuestion < test.questions.length - 1 ? (
159 <button
160 onClick={() => setCurrentQuestion(currentQuestion + 1)}
161 >
162 Next
163 </button>
164 ) : (
165 <button
166 onClick={handleSubmitTest}
167 disabled={isSubmitting}
168 className="submit-btn"
169 >
170 {isSubmitting ? 'Submitting...' : 'Submit Test'}
171 </button>
172 )}
173 </div>
174 </main>
175 </div>
176 );
177};
178 
179export default CodingTest;

Additional Resources

SDKs & Libraries

  • JavaScript/Node.js: Official npm package
  • Python: PyPI package with full typing support
  • PHP: Composer package for Laravel/Symfony
  • Java: Maven/Gradle dependency
  • C#/.NET: NuGet package

Community Examples

  • React + TypeScript: Complete frontend implementation
  • Vue.js Integration: Component library
  • Angular Service: Injectable API service
  • Express.js Middleware: Backend integration
  • Django REST: Python web framework integration

Need help with integration? Check out our to test endpoints interactively, or reach out to our support team.