We currently maintain C# and Python sample code in a GitHub repo. Sections from those samples are listed below to illustrate common survey interactions. Sample survey data is available for testing your code.
Before starting, ensure that your development environment is properly configured by following the steps below.
Environment Setup
Here are the setup instructions to configure your environment to run the code samples.
- Activate the Surveys API.
- Obtain service account credentials:
- Navigate to the Service accounts page in the Developers Console.
- Select the project created in step 1.
- Click Create Service Account
- Fill in the field for "Service account name". Note the Service account ID, which is used in some sample code.
- Click Furnish a new private key, and select JSON.
- Click Create.
- Rename the downloaded JSON file as
account_secret.jsonand place in the same directory as the sample code.
- Continue with language specific setup:
- Python: Install the Google API Python client library:
pip install --upgrade google-api-python-client - C#: Install the Google.Apis.Surveys.v2 NuGet Client Library.
- Python: Install the Google API Python client library:
Getting a Surveys Service object
Before running commands on a survey, you'll need to get a Surveys Service object:
Python
json_keyfile_name = 'account_secret.json'
scopes = [
'https://www.googleapis.com/auth/surveys',
'https://www.googleapis.com/auth/surveys.readonly',
'https://www.googleapis.com/auth/userinfo.email',
]
try:
credentials = ServiceAccountCredentials.from_json_keyfile_name(json_keyfile_name, scopes)
http = httplib2.Http()
auth_http = credentials.authorize(http)
except clientsecrets.InvalidClientSecretsError, e:
print ('Unable to setup authorization with the given credentials. %s'
% e)
return
surveys_service = build('surveys', 'v2', http=auth_http)
C#
var scopes = new[] {
SurveysService.Scope.Surveys,
SurveysService.Scope.SurveysReadonly,
SurveysService.Scope.UserinfoEmail };
GoogleCredential credential;
using (var stream = new FileStream(accountSecretFileName, FileMode.Open, FileAccess.Read))
{
credential = GoogleCredential.FromStream(stream).CreateScoped(scopes);
}
var surveysService = new SurveysService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
});
Common survey interactions
The following are examples of the most common methods to interact with Google Surveys.
Create a survey
Python
body_def = {
'title': 'Student cell phone ownership',
'description': 'Ownership of cell phones, targeted towards students.',
'owners': owner_emails,
'wantedResponseCount': 100,
'audience': {
'country': 'US',
'languages': ['en-US'],
'populationSource': 'androidAppPanel',
'mobileAppPanelId': 'agxzfjQwMi10cmlhbDJyIAsSCVBhbmVsSW5mbyIRc3R1ZGVudHNfdmVyaWZpZWQM',
},
'questions': [
{
'question': 'Do you own a cell phone?',
'type': 'singleAnswer',
'answers': [
'Yes',
'No'],
'thresholdAnswers': [
'Yes'],
},
{
'question': 'What type of cell phone do you own?',
'type': 'singleAnswer',
'answers': [
'Android phone',
'iPhone',
'Other'],
'thresholdAnswers': [
'Android phone'],
},
{
'question': 'What brand is your Android phone?',
'type': 'singleAnswer',
'answers': [
'Google',
'Samsung',
'LG',
'Other'],
}
]
}
survey = surveys_service.surveys().insert(body=body_def).execute()
C#
List<string> langs = new List<string>();
langs.Add("en-US");
SurveyAudience audience = new SurveyAudience()
{
Country = "US",
Languages = langs
};
List<SurveyQuestion> questions = new List<SurveyQuestion>();
SurveyQuestion question = new SurveyQuestion()
{
Type = "numericOpenEnded",
Question = "How much did you pay for your last phone?",
UnitOfMeasurementLabel = "$",
SingleLineResponse = true,
OpenTextPlaceholder = "enter amount here",
};
questions.Add(question);
Survey newSurvey = new Survey()
{
Owners = owners,
Description = "What phones do people buy and how much do they pay?",
Title = "Phone purchase survey",
WantedResponseCount = 110,
Audience = audience,
Questions = questions,
};
Survey survey = surveysService.Surveys.Insert(newSurvey).Execute();
Examine a survey
After creating a survey, you can examine its contents:
Python
survey = surveys_service.surveys().get(surveyUrlId=survey_id).execute()
C#
Survey survey = surveysService.Surveys.Get(surveyId).Execute();
List surveys
Obtain a list of your surveys.
Python
surveys = surveys_service.surveys().list().execute()
C#
var surveyListResponse = surveysService.Surveys.List().Execute();
Start a survey
Here's how to start a survey after it has been successfully reviewed by the Google Surveys team.
Python
if max_cost_per_response:
json_spec = {'maxCostPerResponseNanos': max_cost_per_response}
else:
json_spec = {}
surveys_service.surveys().start(resourceId=survey_id, body=json_spec).execute()
C#
Survey newSurvey = new Survey()
{
State = "running",
};
Survey survey = surveysService.Surveys.Update(newSurvey, surveyId).Execute();
Get survey results
After a survey has finished running, you can get the survey results.
Python
survey = surveys_service.results().get_media(surveyUrlId=survey_id).execute()
C#
FileStream fileSteam = new FileStream(resultFile, FileMode.Create);
surveysService.Results.Get(surveyId).Download(fileSteam);
Delete a survey
Python
surveys_service.surveys().delete(surveyUrlId=survey_id).execute()
C#
surveysService.Surveys.Delete(surveyId).Execute();
Sample Survey Data
You can use the Google Surveys API to get publicly available example surveys to test your code.
