answers.upvote()
Casts an upvote on an answer to indicate it is helpful or correct.
Syntax
Section titled “Syntax”async upvote(questionId: number, answerId: number): Promise<AnswerSummaryResponseModel>
Parameters
Section titled “Parameters”Parameter | Type | Required | Description |
---|---|---|---|
questionId | number | Yes | The unique identifier of the question that contains the answer |
answerId | number | Yes | The unique identifier of the answer to upvote |
Return Value
Section titled “Return Value”Returns a Promise<AnswerSummaryResponseModel>
containing updated answer summary information including the new vote count and score.
Examples
Section titled “Examples”Basic Upvote
Section titled “Basic Upvote”import { StackOverflowSDK } from 'so-teams-sdk';
const sdk = new StackOverflowSDK({ accessToken: 'your-access-token', baseUrl: 'https://[your-site].stackenterprise.co/api/v3'});
// Upvote an answerconst result = await sdk.answers.upvote(123, 456);console.log(`Answer score is now: ${result.score}`);
Upvote with Feedback
Section titled “Upvote with Feedback”try { const answerBefore = await sdk.answers.get(123, 456); console.log(`Current score: ${answerBefore.score}`);
const result = await sdk.answers.upvote(123, 456);
console.log(`Score after upvote: ${result.score}`); console.log(`Score increased by: ${result.score - answerBefore.score}`);} catch (error) { console.error('Failed to upvote:', error.message);}
Conditional Upvoting
Section titled “Conditional Upvoting”async function upvoteIfHelpful(questionId: number, answerId: number) { try { // Get current answer state const answer = await sdk.answers.get(questionId, answerId);
// Check if we can and should upvote if (answer.score < 10) { // Only upvote if score is reasonable const result = await sdk.answers.upvote(questionId, answerId); console.log(`Upvoted answer ${answerId}, new score: ${result.score}`); return result; } else { console.log('Answer already has high score, skipping upvote'); return answer; } } catch (error) { console.error('Error in conditional upvote:', error.message); throw error; }}
await upvoteIfHelpful(123, 456);
Team Context
Section titled “Team Context”// Using team contextconst teamSDK = sdk.forTeam('team-123');const result = await teamSDK.answers.upvote(123, 456);
// Or with direct client initializationimport { AnswerClient } from 'so-teams-sdk';const teamAnswerClient = new AnswerClient(config, 'team-123');const voteResult = await teamAnswerClient.upvote(123, 456);
Handling Vote State Changes
Section titled “Handling Vote State Changes”import StackOverflowSDK, { ForbiddenError } from 'so-teams-sdk';
async function toggleUpvote(questionId: number, answerId: number) { try { // Try to upvote const result = await sdk.answers.upvote(questionId, answerId); console.log('Upvote successful:', result.score); return { action: 'upvoted', score: result.score }; } catch (error) { if (error instanceof ForbiddenError && error.message.includes('already voted')) { // If already upvoted, remove the upvote const result = await sdk.answers.removeUpvote(questionId, answerId); console.log('Upvote removed:', result.score); return { action: 'removed_upvote', score: result.score }; } else { console.error('Vote error:', error.message); throw error; } }}
const voteResult = await toggleUpvote(123, 456);console.log(`Action: ${voteResult.action}, New score: ${voteResult.score}`);
Error Handling
Section titled “Error Handling”This method can throw the following errors:
Error Type | Status Code | Description |
---|---|---|
AuthenticationError | 401 | Invalid or missing authentication token |
TokenExpiredError | 401 | Authentication token has expired |
ForbiddenError | 403 | Cannot vote (already voted, own answer, insufficient permissions) |
NotFoundError | 404 | Question or answer with the specified ID does not exist |
SDKError | Various | Other API or network errors |
Example Error Handling
Section titled “Example Error Handling”import StackOverflowSDK, { NotFoundError, ForbiddenError } from 'so-teams-sdk';
const sdk = new StackOverflowSDK({ accessToken: 'your-access-token', baseUrl: 'https://[your-site].stackenterprise.co/api/v3'});
try { const result = await sdk.answers.upvote(123, 456); console.log('Upvote successful, new score:', result.score);} catch (error) { if (error instanceof NotFoundError) { console.error('Answer not found'); } else if (error instanceof ForbiddenError) { if (error.message.includes('already voted')) { console.error('You have already voted on this answer'); } else if (error.message.includes('own answer')) { console.error('Cannot vote on your own answer'); } else { console.error('Vote not allowed:', error.message); } } else { console.error('Failed to upvote:', error.message); }}
Common Vote Restrictions
Section titled “Common Vote Restrictions”async function safeUpvote(questionId: number, answerId: number) { try { const result = await sdk.answers.upvote(questionId, answerId); return { success: true, score: result.score }; } catch (error) { if (error instanceof ForbiddenError) { if (error.message.includes('already voted')) { return { success: false, reason: 'already_voted' }; } else if (error.message.includes('own answer')) { return { success: false, reason: 'own_answer' }; } else if (error.message.includes('reputation')) { return { success: false, reason: 'insufficient_reputation' }; } } return { success: false, reason: 'error', message: error.message }; }}
const result = await safeUpvote(123, 456);if (result.success) { console.log('Upvoted successfully, new score:', result.score);} else { console.log('Could not upvote:', result.reason);}
- Users cannot vote on their own answers
- Each user can only vote once per answer (upvote OR downvote, not both)
- If a user has already upvoted an answer, calling this method again will typically result in a
ForbiddenError
- To change an upvote to a downvote, you must first remove the upvote using
removeUpvote()
, then calldownvote()
- Voting may require a minimum reputation level depending on the platform configuration
- The returned
AnswerSummaryResponseModel
contains updated vote-related information - Vote counts and scores are updated immediately and reflected in the response
- Some answers may be protected from voting due to special circumstances (locked, deleted, etc.)