Actions

RemoteControl 2 API: Difference between revisions

From LimeSurvey Manual

m (Text replacement - " enclose="div"" to "")
 
(59 intermediate revisions by 17 users not shown)
Line 4: Line 4:
=Introduction=
=Introduction=


LimeSurvey RemoteControl 2 is a XML-RPC/JSON-RPC based web service available in LimeSurvey 2.0 or later. The old [RemoteControl] will not be available any longer in version 2.
LimeSurvey RemoteControl 2 is a XML-RPC/JSON-RPC based web service available in LimeSurvey 2.0 or more recent which offers '''various [https://api.limesurvey.org/classes/remotecontrol_handle.html API functions]'''.  


LSRC2 makes it possible for developers to control specific functionality of LimeSurvey from any other application, without being restricted to PHP as a programming language.
LSRC2 makes it possible for developers to control specific functionality of LimeSurvey from any other application, without being restricted to PHP as a programming language.
Line 27: Line 27:
== How to configure LSRC2==
== How to configure LSRC2==


In a default LimeSurvey installation LSRC2 is disabled. In order to use LSRC2 you must first enable the service, and then adjust the settings to suit your needs. To enable LSRC2 login to the LimeSurvey administration, go to [[Global settings]], choose the tab 'Services' and select one of the two RPC services (XML-RPC or JSON-RPC) service.
 
In a default LimeSurvey installation LSRC2 is disabled. In order to use LSRC2 you must first enable the service, and then adjust the settings to suit your needs. To enable LSRC2 login to the LimeSurvey administration, go to [[Global settings]], choose the tab 'Interfaces' and select one of the two RPC services (XML-RPC or JSON-RPC) service.
 
 
{{Alert|'''Do not forget''' to activate the LimeSurvey API first! To do this, access your global configuration, click on [[Global_settings#Interfaces|Interfaces]] and enable the API setting.}}


== Security==
== Security==
Line 35: Line 39:
=How to use LSRC2=
=How to use LSRC2=


The basic LSRC2 URL is: http://<your_domain>/<your_limesurvey_dir>/index.php/admin/remotecontrol
The LSRC2 URL are shown on [[Global_settings#Interfaces|global settings]], it was adapted to your current configuration.


LSRC2 fully complies to the [http://www.xmlrpc.com/ XML-RPC specification] and JSON-RPC version 1 specifications. We recommend in general to use JSON-RPC because it is well tested and has a much smaller footprint than XML-RPC.
LSRC2 fully complies to the [http://www.xmlrpc.com/ XML-RPC specification] and [https://www.jsonrpc.org/specification_v1 JSON-RPC version 1] specifications. We recommend in general to use JSON-RPC because it is well tested and has a much smaller footprint than XML-RPC.


LSRC2 offers a lot of functions. Please check the automatically generated [http://api.limesurvey.org/classes/remotecontrol_handle.html API Documentation].
LSRC2 offers a lot of functions. Please check the automatically generated [http://api.limesurvey.org/classes/remotecontrol_handle.html API Documentation].
Line 49: Line 53:


<source lang=php>
<source lang=php>
function get_session_key(string $username, string $password)
function get_session_key(string $username, string $password, string $plugin = 'Authdb')
</source>
 
'''Return on success''': (string) session key.
 
'''Return on error''':  for protocol-level errors (invalid format etc), an error message. For invalid username and password, returns a null error and the result body contains a 'status' name-value pair with the error message.
 
=== release_session_key ===
 
Using this function you can close a previously opened XML-RPC/JSON-RPC session.
 
<source lang=php>
function release_session_key(string $sSessionKey)
</source>
</source>


Line 67: Line 59:
! Parameter !! Description
! Parameter !! Description
|-
|-
| sSessionKey || Auth credentials
| username || The username used for connexion
|-
|}
 
'''Return''': Always 'OK' (string)
 
== Site ==
 
=== get_site_settings ===
 
Function to query site settings. Can only be used by administrators.
 
<source lang=php>
function get_site_settings( string $sSessionKey, string $sSetttingName)
</source>
 
{| class="wikitable"
! Parameter !! Description
|-
|-
| sSessionKey || Auth credentials
| password || The password used for connexion
|-
|-
| sSetttingName || Name of the setting to get
| plugin {{NewIn|3.2.0}} || The Auth plugin to be used
|-
|-
|}
|}


'''Return on success''': (string) Setting's value
'''Return on success''': (string) session key.


'''Return on failure''': (string) Error message
'''Return on error''': for protocol-level errors (invalid format etc), an error message. For invalid username and password, returns a null error and the result body contains a 'status' name-value pair with the error message.


== Users ==
=== release_session_key ===


=== list_users ===
Using this function you can close a previously opened XML-RPC/JSON-RPC session.
 
Function to return the ids and info of users.


<source lang=php>
<source lang=php>
function list_users(string $sSessionKey)
function release_session_key(string $sSessionKey)
</source>
 
{| class="wikitable"
! Parameter !! Description
|-
| sSessionKey || Super-admin's auth credentials.
|-
|}
 
'''Return on success''': (array) The list of users
 
'''Return on failure''': (array) Failure status:
*No users found
*Invalid session key
*No permission (super admin is required)
 
== Surveys ==
 
===add_survey===
 
RPC Routine to add an empty survey with minimum details
 
Parameters:
 
sSessionKey (string)  Auth credentials
 
iSurveyID    (int),    The wish id of the Survey to add
 
sSurveyTitle    (string),  Title of the new Survey
 
sSurveyLanguage    (string),  Default language of the Survey
 
sformat    (string),  Question appearance format (S|G|A)
 
Returns:
*On success: (int) $iNewSurveyID
*On failure: (array) Failure status
**Invalid session key
**No permission
**Faulty parameters
**Creation Failed
 
===delete_survey===
 
RPC Routine to Delete a survey
 
Parameters:
 
sSessionKey (string), Auth credentials
 
iSurveyID (int), The Survey to delete
 
Returns:
*On success: Status =>OK (array)
*On failure: (array) Failure status
**Invalid session key
**No permission
 
===import_survey===
 
RPC Routine to import a survey from lss,csv,xls or survey zip archive.
 
Parameters:
 
sSessionKey (string)  Auth credentials
 
sImportData  (string) String containing the BASE 64 encoded data of a lss,csv,xls or survey zip archive
 
sImportDataType    (string),    The format of the import file (lss,csv,xls or zip)
 
sNewSurveyName    (string),  The optional new name of the survey (base language)
 
DestSurveyID    (int), This is the new ID of the survey - if already used a random one will be taken instead
 
Returns:
*On success: (int) $iNewSurveyID
*On failure: (array) Failure status
**Invalid session key
**No permission
**Import error
 
=== get_survey_properties ===
 
RPC Routine to get properties of a survey
 
<source lang=php>
function get_survey_properties( string $sSessionKey, int $iSurveyID, array $aSurveySettings)
</source>
</source>


Line 197: Line 83:
|-
|-
| sSessionKey || Auth credentials
| sSessionKey || Auth credentials
|-
| iSurveyID || ID of the survey
|-
| aSurveySettings || An array of strings containing the properties to return
|-
|-
|}
|}


'''Return on success''': (string) The requested value
'''Return''': Always 'OK' (string)
 
'''Return on failure''': (array) Failure status : '''Invalid survey ID''', '''Invalid session key''', '''No permission''', '''No valid Data'''
 
{| class="wikitable"
|+ Available properties
| | active
| | autonumber_start
| | emailnotificationto
| | nokeyboard
| | showwelcome
 
|-
| | additional_languages
| | autoredirect
| | emailresponseto
| | owner_id
| | showxquestions
 
|-
| | admin
| | bounce_email
| | expires
| | printanswers
| | sid
 
|-
| | adminemail
| | bounceaccountencryption
| | faxto
| | publicgraphs
| | startdate
 
|-
| | alloweditaftercompletion
| | bounceaccounthost
| | format
| | publicstatistics
| | template
 
|-
| | allowjumps
| | bounceaccountpass
| | googleanalyticsapikey
| | refurl
| | tokenanswerspersistence
 
|-
| | allowprev
| | bounceaccounttype
| | googleanalyticsstyle
| | savetimings
| | tokenlength
 
|-
| | allowregister
| | bounceaccountuser
| | htmlemail
| | sendconfirmation
| | usecaptcha
 
|-
| | allowsave
| | bounceprocessing
| | ipaddr
| | showgroupinfo
| | usecookie
 
|-
| | anonymized
| | bouncetime
| | language
| | shownoanswer
| | usetokens
 
|-
| | assessments
| | datecreated
| | listpublic
| | showprogress
| |
 
|-
| | attributedescriptions
| | datestamp
| | navigationdelay
| | showqnumcode
| |
|}
 
===set_survey_properties===
 
RPC Routine to set properties of a survey
 
'''Parameters''':
 
sSessionKey (string)  Auth credentials
 
iSurveyID (integer) -  ID of the survey
 
aSurveySettings    (array),    An assosiative array with the name-value  pair of the properties to set
 
'''Returns''':
 
*On success: (array) The result of the change for each property
*On failure: (array) Failure status
**Invalid survey ID
**Invalid session key
**No permission
**No valid Data
 
'''Available properties''':
 
Properties available for changing are all those defined in get_survey_properties with the following exceptions
 
* Allways
** sid
** language
** additional_languages
** active
* When survey active
** anonymized
** datestamp
** savetimings
** ipaddr
** refurl
 
===list_surveys===
 
RPC Routine to list the ids and info of surveys belonging to a user.
 
    * If user is admin he can get surveys of every user (parameter sUser) or all surveys (sUser=null)
 
    * Else only the syrveys belonging to the user requesting will be shown.
 
Parameters:
 
sSessionKey (string)  Auth credentials
 
sUser (string) -  The users surveys to list
 
Returns:
*On success: (array) Survey's properties
*On failure: (array) Failure status
**Invalid user
**Invalid session key
**No permission
**No surveys found
 
Survey's properties:
 
{|
|property||type
|-
|sid||integer
|-
|surveyls_title||string
|-
|startdate||date
|-
|expires||date
|-
|active||y/n
|-
|
|}
 
===activate_survey===
 
RPC Routine that launches a newly created survey (sets active -available for users)
 
Parameters:
 
sSessionKey (string)  Auth credentials
 
SurveyID (integer) -  ID of the survey
 
Returns
*On success: (array) The result of the activation
*On failure: (array) Failure status
**Invalid Survey ID
**Activation Error
**Invalid session key
**No permission
 
===export_statistics===
 
RPC routine to export statistics of a survey to a user.
 
Parameters:
 
sSessionKey (string)  Auth credentials
 
SurveyID (integer) -  ID of the survey
 
docType (string) - Type of document to generate
 
sLanguage (string) Optional language of the survey to use (if not set, default language is selected)
 
graph (string) - Optional parameter to enable graphs (0|1)
 
Returns
*On success: (string) Base64 encoded string with the statistics file
*On failure: (array) Failure status
**Invalid Survey ID
**Invalid session key
**No permission
 
===get_summary===
 
RPC routine to get survey summary, regarding token usage and survey participation.
 
Parameters:
 
sSessionKey (string) - Auth credentials
 
iSurveyID (integer) -  ID of the survey
 
sStatname (string) - The statistic to return or 'all' to get an array of all statistics
 
Returns
*On success: (string) Base64 encoded string with the statistics file
*On failure: (array) Failure status
**No available data
**No such property
**Invalid session key
**No permission
 
Available statistics:
 
{|
|Survey stats||Token stats
|-
|completed_responses||token_count
|-
|incomplete_responses||token_invalid
|-
|full_responses||token_sent
|-
|||token_opted_out
|-
|||token_completed
|-
|
|}
 
===add_language===
 
RPC Routine to add a language to an existing survey
 
Parameters:
 
session key (string) - The session key
 
SurveyID (integer) -  ID of the survey
 
aLanguage (string) - The language shortcut for the new language to be added. Note: If the language is already in that survey no error will be thrown.
 
Return values:
*On success: (array) status=>OK
*On failure: (array) Any other status
**Invalid survey ID
**Invalid language
**Error
**Invalid session key
**No permission
 
===delete_survey_language===
 
RPC Routine to delete a language of an existing survey
 
Parameters:
 
session key (string) The session key
 
SurveyID (integer) -  ID of the survey
 
aLanguage (string) - The language shortcut for the language to be removed. Note: If the language is not part of that survey no error will be thrown.
 
Return values:
*On success: (array) status=>OK
*On failure: (array) Any other status
**Invalid survey ID
**Invalid language
**Cannot remove base language
**Error
**No permission
**Invalid session key
 
===get_language_properties===
 
RPC Routine to get survey language properties
 
Parameters:
 
sSessionKey (string) - Auth credentials
 
iSurveyID (integer) -  ID of the survey
 
aSurveyLocaleSettings    (array) -  An array with the properties to return
 
slang (string)    - The language to use
 
Returns:
*On success: (string) the requested value
*On failure: (array) Failure status
**Invalid survey ID
**Invalid session key
**No permission
**No valid Data
 
Available parameters:
 
{|
|  ||  ||  ||
|-
|    surveyls_survey_id            ||    surveyls_url                  ||    surveyls_email_register_subj  ||    email_admin_notification_subj
|-
|    surveyls_language            ||    surveyls_urldescription      ||    surveyls_email_register      ||    email_admin_notification
|-
|    surveyls_title                ||    surveyls_email_invite_subj    ||    surveyls_email_confirm_subj  ||    email_admin_responses_subj
|-
|    surveyls_description          ||    surveyls_email_invite        ||    surveyls_email_confirm        ||    email_admin_responses
|-
|    surveyls_welcometext          || surveyls_email_remind_subj      ||    surveyls_dateformat          ||    surveyls_numberformat
|-
|surveyls_endtext              ||    surveyls_email_remind        ||    surveyls_attributecaptions    || 
|}
 
===set_language_properties===
 
RPC Routine to set survey language properties
 
Parameters:
 
sSessionKey (string) - Auth credentials
 
iSurveyID (integer) -  ID of the survey
 
aSurveyLocaleData    (array) -  An assosiative array with the key-value pairs of properties to set. Invalid fieldnames or fields that may not be modified are ignored.
 
sLanguage (string)    - The language to use
 
Returns:
*On success: (string) Result for each parameter set
*On failure: (array) Failure status
**Invalid survey ID
**Invalid language
**Invalid session key
**No permission
**No valid Data
 
Allowed Parameters:
 
All those defined in get-language_properties except:
*surveyls_language
*surveyls_survey_id
 
== Groups of Questions ==
 
===add_group===
 
RPC Routine to add an empty group with minimum details.
 
    * Used as a placeholder for importing questions.
 
    * Returns the groupid of the created group.
 
Parameters:
 
sSessionKey (string) - Auth credentials
 
iSurveyID (integer) -  ID of the surveythat the group will be added
 
sGroupTitle    (string) -  Name of the new group
 
sGroupDescription (string) - Optional description of the group
 
Returns:
*On success: (int) The ID of the new group
*On failure: (array) Failure status
**Invalid survey ID
**Error:Survey is active and not editable
**Invalid session key
**No permission
**Creation Failed
 
===delete_group===
 
RPC Routine to delete a group of a survey
 
Parameters:
 
sSessionKey (string) - Auth credentials
 
iSurveyID (integer) -  ID of the survey that the group belongs
 
sGroupID    (int) -  Id of the group to delete
 
Returns:
*On success: (int) The ID of the deleted group
*On failure: (array) Failure status
**Invalid Survey ID
**Invalid Group ID
**Error:Survey is active and not editable
**Invalid session key
**No permission
**Group deletion failed
 
===import_group===
 
RPC Routine to import a group - imports lsg,csv
 
Parameters:
 
sSessionKey (string) - Auth credentials
 
iSurveyID (integer) -  The id of the survey that the group will belong
 
sImportData    (string) -  String containing the BASE 64 encoded data of a lsg,csv
 
sGroupDescription (string) -The format of the importfile in the stream (lsg|csv)
 
sNewGroupName (string) - Optional new name for the group
 
sNewGroupDescription (string) - Optional new description for the group
 
Returns:
*On success: (int) The ID of the new group
*On failure: (array) Failure status
**Invalid survey ID
**Error:Survey is active and not editable
**Invalid extension
**Error: Invalid LimeSurvey group structure XML
**Invalid session key
**No permission
**Import Error
 
===get_group_properties===
 
RPC Routine to return properties of a group of a survey
 
Parameters:
 
sSessionKey (string) - Auth credentials
 
iGroupID (integer) -  The id of the group to get properties of
 
aGroupSettings    (array) -  Array containing the properties to request.
 
Returns:
*On success: (array) The requested properties
*On failure: (array) Failure status
**Error: Invalid group ID
**No valid Data
**Invalid session key
**No permission
 
Available properties:
 
{|
| ||
|-
|gid||description
|-
|sid||language
|-
|group_name||randomization_group
|-
|group_order||grelevance
|-
|
|}
 
===set_group_properties===
 
RPC Routine to set properties of a group of a survey
 
Parameters:
 
sSessionKey (string) - Auth credentials
 
iGroupID (integer) -  The id of the group to set properties to
 
aGroupData    (array) -  Assosiative Array containing key-value pairs of the properties to set.
 
Returns:
*On success: (array) The result of each set action
*On failure: (array) Failure status
**Error: Invalid group ID
**No valid Data
**Group with dependencies - Order cannot be changed
**Invalid session key
**No permission
 
Available properties:
 
{|
| ||
|-
|||description
|-
|||language
|-
|group_name||randomization_group
|-
|group_order||grelevance
|-
|
|}
 
===list_groups===
 
RPC Routine to return the ids and info of groups belonging to survey
 
Parameters:
 
sSessionKey (string) - Auth credentials
 
iSurveyID (integer) -  The id of the survey to get groups of
 
Returns:
*On success: (array) The list of the groups
*On failure: (array) Failure status
**Invalid Survey ID
**No groups found
**Invalid session key
**No permission
 
== Questions ==
 
===delete_question===
 
RPC Routine to delete a question of a survey
 
Parameters:
 
sSessionKey (string)  Auth credentials
 
iQuestionID  (int) Id of the question to delete
 
Returns:
*On success: (int)id of the deleted Question
*On failure: (array) Failure status
**Invalid session key
**No permission
** Invalid question ID
**Survey is active and not editable
**Cannot delete Question. Others rely on this question
**Error
 
===import_question===
 
RPC Routine to import a question - imports lsq,csv
 
Parameters:
 
sSessionKey (string) - Auth credentials
 
iSurveyID  (int) - Id of the survey that the new questions belongs
 
iGroupID (int) - Id of the group that the new questions belongs
 
sImportData (string) - String containing the BASE 64 encoded data of a lsg,csv
 
sImportDataType (string)  - Format of the input stream (lsq,csv)
 
sMandatory (string) - Optional Mandatory question option (default to No)
 
sNewQuestionTitle (string) - Optional new title for the question
 
sNewqQuestion (string) - An optional new question
 
sNewQuestionHelp (string) - An optional new question help text
 
Returns:
*On success: (int) Id of the new Question
*On failure: (array) Failure status
**Invalid session key
**No permission
**Invalid survey ID
**Invalid group ID
**Survey is active and not editable
**Invalid extension
**Invalid LimeSurvey question structure XML
 
===get_question_properties===
 
RPC Routine to return properties of a question of a survey
 
Parameters:
 
sSessionKey (string)  Auth credentials
 
iQuestionID  (int) Id of the question to get properties of
 
aQuestionSettings (array) The properties to get
 
sLanguage (string) Optional parameter language for multilingual questions
 
Returns:
*On success: (array) The requested properties
** When there are no attributes for the question, the result for the "attributes" key is set to "No available attributes".
*On failure: (array) Failure status
**Invalid session key
**No permission
**Invalid questionid
**Invalid language
**No valid Data
 
Available Properties:
 
{|
|  ||  ||  ||
|-
|gid||type||help||language
|-
|parent_qid||title||other||scale_id
|-
|sid||question||mandatory||same_default
|-
|gid||preg||question_order||relevance
|-
|subquestions||attributes||attributes_lang||answeroptions
|-
|
|}
 
===set_question_properties===
 
RPC Routine to set question properties
 
Parameters:
 
sSessionKey (string) - Auth credentials
 
iQuestionID  (int) - Id of the question to get properties of
 
aQuestionData (array)  - An array with the particular fieldnames as keys and their values to set on that particular question
 
sLanguage (string)  -  Optional parameter language for multilingual questions
 
Returns:
*On success: (array) The resilt of the set of each property
*On failure: (array) Failure status
**Invalid session key
**No permission
**Invalid questionid
**Invalid language
**Questions with dependencies - Order cannot be changed
**No valid Data
 
Available Properties:
 
{|
|  ||  ||
|-
|help|| ||
|-
|title||other||scale_id
|-
|question||mandatory||same_default
|-
|preg||question_order||relevance
|-
|
|}
 
===list_questions===
 
RPC Routine to return the ids and info of questions of a survey/group.
 
Parameters:
 
sSessionKey (string) - Auth credentials
 
iSurveyID (int) - Id of the survey to get questions of
 
iGroupID  (int) - Optional Id of the group to get questions of
 
sLanguage (string)  -  Optional parameter language for multilingual questions
 
Returns:
*On success: (array) The list of the questions
*On failure: (array) Failure status
**Invalid session key
**No permission
**Invalid questionid
**Invalid language
**Invalid survey ID
**Missmatch in surveyid and groupid
**No questions found
 
== Tokens and Participants ==
 
=== Token Properties  ===
 
The following properties of tokens can be read or set:
 
{| class="wikitable"
! Property !! Type !! Description
|-
|tid || int || Token ID; read-only property
|-
|completed ||  ||
|-
|participant_id || ||
|-
|language || string ||
|-
|usesleft || ||
|-
|firstname || String || Participant's first name
|-
|lastname || String || Participant's last name
|-
|email || String || Participant's e-mail address
|-
|blacklisted || ||
|-
|validfrom || ||
|-
|sent || ||
|-
|validuntil || ||
|-
|remindersent || ||
|-
|mpid || ||
|-
|emailstatus || ||
|-
|remindercount || ||
|-
|}
 
=== activate_tokens ===
 
RPC routine to to initialise the survey's collection of tokens where new participant tokens may be later added
 
<source lang=php>
public function activate_tokens($sSessionKey, $iSurveyID, $additional_attributes)
</source>
 
{| class="wikitable"
! Parameter !! Type !! Description
|-
| sSessionKey || string || Auth credentials
|-
| iSurveyID || int || Id of the Survey
|-
| additional_attributes || array of integer || Any additional attribute fields to create. Just give the attribute IDs.
|-
|}
 
'''Return on success''': (array) Status OK
 
'''Return on failure''': (array) Failure status
*Invalid session key
*No permission
*Invalid survey ID
*Token table could not be created
 
===add_participants===
 
Using this function you can add new entries to your token table. You can also set if for these new entries a unique token key is automatically created. Please note that this function does not check for duplicate content in any of the fields, except for token keys created by the function itself.
 
<source lang=php>
public add_participants($sSessionKey, $iSurveyID, $participantData, $createTokenKey)
</source>
 
{| class="wikitable"
! Parameter !! Type !! Description
|-
| $sSessionKey || string || Auth credentials
|-
| $iSurveyID || int || Id of the Survey
|-
| $participantData || (array) || 2-dimensional array/structure containing your participants data. Example:
<source lang="javascript">[ {"email":"me@example.com","lastname":"Bond","firstname":"James"} ]</source>
|-
| $createTokenKey || boolean || Set this to true if you want a token key created automatically for each entry - if your participant data already included a [token] field it will be overwritten
|-
|}
 
'''Return''': array(struct) On success: Structure containing your participants data plus the token ID and (if applicable) the new token. Example:
<source lang="javascript">
[ {"email":"me@example.com","lastname":"Bond","firstname":"James","tid":"1","token":"auc82gar58dpcg6"} ]
</source>
 
'''Return''': string Failure Status: "Invalid session key", "No permission", "Invalid survey ID"


===delete_participants===
== List of functions ==


RPC Routine to delete multiple participants of a Survey
'''All functions including descriptions can be found at our developers [http://api.limesurvey.org/classes/remotecontrol_handle.html RemoteControl functions API page].'''


Parameters:


sSessionKey (string) - Auth credentials
Also, you can publish your API (check out global settings) and look at it directly.


iSurveyID (int) - Id of the survey to get questions of


aTokenIDs  (array) - IId of the tokens/participants to delete
{{Alert|The parameter structure uses arrays of values - you *must* send the values in the API expected order (see [https://www.jsonrpc.org/specification_v1#a1.1Requestmethodinvocation jsonrpc specification]).}}


Returns:
= Example and helper =
*On success: (array) Array of deletion status for each participant
*On failure: (array) Failure status
**Invalid session key
**No permission
**Invalid survey ID
**No token table


===get_participant_properties===
== PHP Example ==


RPC Routine to return settings of a token/participant of a survey
To include JSON-RPC in your application, you can write an application using the light-weight jsonRPCClient from the [https://github.com/weberhofer/jsonrpcphp jsonrpcphp Github repository]. The library can also get included [https://getcomposer.org/download/ by composer calling]
 
Parameters:
 
sSessionKey (string) -  Auth credentials
 
iSurveyID  (int) - Id of the Survey to get token properties
 
iTokenID (int) - Id of the participant to check
 
aTokenProperties (array) - The properties to get. All properties defined in [[#Token Properties]] can be read.
 
Returns:
*On success: (array) Array of requested values
*On failure: (array) Failure status
**Invalid session key
**No permission
**Invalid survey ID
**No token table
**Invalid tokenid
**No valid Data
 
===set_participant_properties===
 
RPC Routine to set properties of a survey participant/token
 
Parameters:
 
sSessionKey (string) -  Auth credentials
 
iSurveyID  (int) - Id of the Survey to set token properties
 
iTokenID (int) - Id of the participant to alter
 
aTokenData (array) - Key - value pair of the properties to set. All writeable properties defined in [[#Token Properties]] can be written.
 
Returns:
*On success: (array) Array of results of changing properties
*On failure: (array) Failure status
**Invalid session key
**No permission
**Invalid survey ID
**No token table
**Invalid tokenid
**No valid Data
 
 
===list_participants===
 
RPC routine to return the IDs and info of token/participants of a survey.
 
Parameters:
 
  sSessionKey (string) -  Auth credentials
  iSurveyID  (int) - Id of the survey to list participants
  iStart (int) - Start id of the token list
  iLimit (int) - Number of participants to return
  bUnused (bool) - If you want unused tokensm, set true
  aAttributes(bool|array) An array of extended attributes that can be requested, besides the default ones (default value to false)
 
Returns:
*On success: (array) Array of Participants info
*On failure: (array) Failure status
**Invalid session key
**No permission
**Invalid survey ID
**No token table
**No Tokens found
 
Note:
 
If you provide the iLimit parameter it is required to provide the iStart parameter.
 
===invite_participants===
 
RPC Routine to invite participants in a survey
 
Parameters:
 
sSessionKey (string) -  Auth credentials
 
iSurveyID  (int) - Id of the survey to send invitation to participants
 
Returns:
*On success: (array)  Array of result of each email send action and count of invitations left to send
*On failure: (array) Failure status
**Invalid session key
**No permission
**Invalid survey ID
**No token table
**No candidate tokens
 
===remind_participants===
 
RPC Routine to send reminder for participants in a survey
 
Parameters:
 
sSessionKey (string) -  Auth credentials
 
iSurveyID  (int) - Id of the survey to send invitation to participants
 
iMinDaysBetween (int) - Optional parameter days from last reminder
 
iMaxReminders (int) - Optional parameter Maximum reminders count
 
Returns:
*On success: (array)  Array of result of each email send action and count of invitations left to send
*On failure: (array) Failure status
**Invalid session key
**No permission
**Invalid survey ID
**No token table
**No candidate tokens
 
== Responses ==
 
===add_response===
 
<source lang=php>
public function add_response($sSessionKey, $iSurveyID, $aResponseData)
</source>
 
RPC Routine to add a response to the survey responses collection.
 
'''Return''': int|array On success: Returns the id of the inserted survey response. On failure array with error information
 
{| class="wikitable"
! Parameter !! Type !! Description
|-
| $sSessionKey || string || Auth credentials
|-
| $iSurveyID || int || Id of the Survey
|-
| $aResponseData || array || The actual response
|-
|}
 
===export_responses===
<source lang=php>
public function export_responses($sSessionKey, $iSurveyID, $sDocumentType, $sLanguageCode=null,
  $sCompletionStatus='all', $sHeadingType='code', $sResponseType='short', $iFromResponseID=null, $iToResponseID=null, $aFields=null)
</source>
 
RPC Routine to export responses. Returns the requested data in the specified format as base64 encoded string.
 
'''Return''': array|string On success: Requested data in the specified format as base 64-encoded string. On failure array with error information
 
'''Note''': If you have huge response sets try only to request a certain number of records at a time otherwise the server may run out of memory.
 
'''Note''': Starting with version 2.0.5 the $iFromResponseID and $iToResponseID parameters refer to the minimum and maximum id's; prior to this version the parameters refered to the record's offset in the table
 
{| class="wikitable"
! Parameter !! Type !! Description
|-
| $sSessionKey || string || Auth credentials
|-
| $iSurveyID || int || Id of the Survey
|-
| $sDocumentType || string || pdf,csv,xls,doc,json
|-
| $sLanguageCode || string || The language to be used
|-
| $sCompletionStatus || string || Optional 'complete','incomplete' or 'all' - defaults to 'all'
|-
| $sHeadingType || string || 'code','full' or 'abbreviated' Optional defaults to 'code'
|-
| $sResponseType || string || 'short' or 'long' Optional defaults to 'short'
|-
| $iFromResponseID || integer || Optional
|-
| $iToResponseID || integer || Optional
|-
| $aFields|| array || Optional Selected fields
|-
|}
 
===export_responses_by_token===
 
<source lang=php>
public function export_responses_by_token($sSessionKey, $iSurveyID, $sDocumentType, $sToken, \
  $sLanguageCode=null, $sCompletionStatus='all', $sHeadingType='code', $sResponseType='short', $aFields=null)
</source>
 
Export responses data of specific token. Returns the requested file as base64 encoded string.
 
'''Return''': array|string On success: Requested file as base 64-encoded string. On failure array with error information
 
{| class="wikitable"
! Parameter !! Type !! Description
|-
| $sSessionKey || string || Auth credentials
|-
| $iSurveyID || int || Id of the Survey
|-
| $sDocumentType || string || pdf,csv,xls,doc,json
|-
| $sToken || string || The token for which responses needed
|-
| $sLanguageCode || string || The language to be used
|-
| $sCompletionStatus || string || Optional 'complete','incomplete' or 'all' - defaults to 'all'
|-
| $sHeadingType || string || 'code','full' or 'abbreviated' Optional defaults to 'code'
|-
| $sResponseType || string || 'short' or 'long' Optional defaults to 'short'
|-
| $aFields|| array || Optional Selected fields
|-
|}
 
=Testing=
 
To test you will have to activate JSON-RPC in global settings. To run a simple self-test go to
 
http://path_to_your_limesurvey_installation/index.php/admin/remotecontrol/test . This will import the example survey, do various things with it and delete it afterwards.
 
The test assumes that you still are using the standard user 'admin' with password 'password'.
 
The client function for this test can be found in /application/controller/admin/remotecontrol.php and the particular function is called test().
 
=Ruby Example=
 
There are some cool things that you can use with the RemoteControl2 API and this is an example of a production use of this. Basically, I, (kobaltz in the forums) have a third party site that I built that controls the users and level of access of each company and their users. From within this site, I have a daemon that will generate participants of the appropriate survey twice an hour. This will use LimeSurvey's Mail Function to send the end user a link to the survey. Administrators of the third party site will get statistical data of the end user filling out the survey as well as a link to review the surveys completed using the same template that the user used to fill it out. Reducing duplicate entry of data made possible with the RemoteControl2 API.
 
==Load Requirements and Declare Values==
You will first need to require the dependencies needed to establish communication with the API. Also, note that there is a username and password field that requires to be stored in plain text. I have a separate API User within my LimeSurvey to handle these calls.
 
<syntaxhighlight lang="ruby" enclose="div">
#!/usr/bin/env ruby
 
require 'net/https'
require 'uri'
require 'json'
 
username = "api_user"
password = "api_user"
</syntaxhighlight>
 
==Module==
 
The below code is used to define the module LimeSurvey. Within this module is an API class. We will use this to create an instance of this module and then call on the API call wherever needed.
 
<syntaxhighlight lang="ruby" enclose="div">
module LimeSurvey
  class API
    def initialize(service_url)
      @uri = URI.parse(service_url)
    end
 
    def method_missing(name, *args)
      post_body = { 'method' => name, 'params' => args, 'id' => 'jsonrpc' }.to_json
      resp = JSON.parse( http_post_request(post_body) )
      raise JSONRPCError, resp['error'] if resp['error']
      resp['result']
    end
 
    def http_post_request(post_body)
      http    = Net::HTTP.new(@uri.host, @uri.port)
      request = Net::HTTP::Post.new(@uri.request_uri)
      request.content_type = 'application/json'
      request.body = post_body
      http.request(request).body
    end
  end
 
  class JSONRPCError < RuntimeError; end
end
</syntaxhighlight>
 
==API Call==
This code is used to create the instance of the LimeSurvey::API module and class. You will want to change the URL to that of your RemoteControl2 URL.
<syntaxhighlight lang="ruby" enclose="div">
survey = LimeSurvey::API.new('http://localhost/limesurvey/index.php?r=admin/remotecontrol')
</syntaxhighlight>
 
==Examples==
This example takes the above code and puts it into play. I create a new session with the RemoteControl2 API and store the session in the variable session_key. You will want to change the ID numbers to the appropriate Survey ID in the examples.
<syntaxhighlight lang="ruby" enclose="div">
system("cls")
session_key = survey.get_session_key(username,password)
puts "Session Key: #{session_key}"
puts "\n"
 
 
response = survey.get_survey_properties(session_key, "863224", ["owner_id"])
puts "Properties:  #{response}"
puts "\n"
 
response = survey.list_surveys(sSessionKey: session_key, sUser: "dkimura")
puts "Survey List:  #{response}"
puts "\n"
 
response = survey.add_participants(
    session_key,
    "863224",
    [email:"james.bond@example.com",lastname:"Bond",firstname:"James"]
  )
puts "Add Participant:  #{response}"
puts "\n"
 
response = survey.invite_participants(
    session_key,
    "863224"
  )
puts "Invite Participant:  #{response}"
 
response = survey.release_session_key(session_key)
puts "Release Session: #{response}"
 
# Grabs a Survey's list of participants and parses through them
# The response is in an array format.
# Each response within the array is in JSON format (How the survey is configured with RemoteControl2)
# Convert the participant response to JSON and then display the token.
response = survey.list_participants(session_key, "593987")
puts "\n"
response_participants = []
response.each do |part|
resps = JSON.parse(part.to_json)
puts "Participant: #{resps['token']}"
puts "\n"
end
</syntaxhighlight>
==Example Return==
 
From the above example, here is the return that I receive. Some of the items are returned as a hash and some items returned as an array of hashes.
 
<syntaxhighlight lang="ruby" enclose="div">
Session Key: piadscbc94vyanxwkdy8f3xii4av2b2w
 
Properties:  {"owner_id"=>"1"}
 
Survey List:  [{"sid"=>"863224", "surveyls_title"=>"Statement of Work v0.12", "startdate"=>nil, "expires"=>nil, "active"=>"Y"}]
 
Add Participant:  [{"email"=>"james.bond@example.com", "lastname"=>"Bond", "firstname"=>"James", "tid"=>"7", "token"=>"pt5ztzxndibkz4j"}]
 
Invite Participant:  {"7"=>{"name"=>"James Bond", "email"=>"james.bond@example.com", "status"=>"OK"}, "status"=>"0 left to send"}
 
Participant: p7m5zmh38wi9mbk
Participant: nssu6ne6ii9wva9
Participant: r9kr2sahn7tfsv9
Participant: a28ci2z9m7ynfgg
Participant: 4ytt5axg9ebdazh
Participant: wswjv2t5v7vh4p7
Participant: fqvxeckgh6vgy3e
Participant: n5p2vfnh7dwx699
Participant: ycsmigup9pagm6z
Participant: 33ztf4g74k2kvx4
 
Release Session: OK
</syntaxhighlight>
 
= PHP Example =
 
To include JSON-RPC in your application, you can write an application using the light-weight jsonRPCClient from the [https://github.com/weberhofer/jsonrpcphp jsonrpcphp Github repository]. The library can also get included by composer calling


<source lang=bash>
<source lang=bash>
Line 1,383: Line 113:
{
{
     "require": {
     "require": {
         "weberhofer/jsonrpcphp": "2.1.0"
         "weberhofer/jsonrpcphp": "~2"
     }
     }
}
}
</source>
</source>


This is a example how to connect to limesurvey:
This is an example how to connect to limesurvey:


<source lang="php">
<source lang="php">
Line 1,398: Line 128:
include_once 'vendor/autoload.php';
include_once 'vendor/autoload.php';


define( 'LS_BASEURL', 'http://localhost/limesurvey/');  // adjust this one to your actual LimeSurvey URL
define( 'LS_RPCURL', 'https://localhost/limesurvey/admin/remotecontrol');  // adjust this one to your actual Remote Control URL
define( 'LS_USER', 'rpcuser' );
define( 'LS_USER', 'rpcuser' );
define( 'LS_PASSWORD', 'mypassword' );
define( 'LS_PASSWORD', 'mypassword' );
Line 1,405: Line 135:
$survey_id=374699;
$survey_id=374699;


// instanciate a new client
// instantiate a new client
$myJSONRPCClient = new \org\jsonrpcphp\jsonRPCClient( LS_BASEURL.'/admin/remotecontrol' );
$myJSONRPCClient = new \org\jsonrpcphp\JsonRPCClient( LS_RPCURL );


// receive session key
// receive session key
$sessionKey= $myJSONRPCClient->get_session_key( LS_USER, LS_PASSWORD );
$sessionKey= $myJSONRPCClient->get_session_key( LS_USER, LS_PASSWORD );


// receive all ids and info of groups belonging to a given survey
// receive surveys list current user can read
$groups = $myJSONRPCClient->list_groups( $sessionKey, $survey_id );
$groups = $myJSONRPCClient->list_surveys( $sessionKey );
print_r($groups, null );
print_r($groups, null );


Line 1,420: Line 150:
</source>
</source>


=JAVA example=
See a [https://gitlab.com/SondagesPro/coreAndTools/twigExtendByPlugins/snippets/1729193 snippet example of list_surveys]
 
== JAVA example ==
To decode and code your json calls you can use the library gson as you can see in the following example:
To decode and code your json calls you can use the library gson as you can see in the following example:


<syntaxhighlight lang="java" enclose="div">
<syntaxhighlight lang="java">
import java.io.IOException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.io.UnsupportedEncodingException;
Line 1,443: Line 175:
JsonElement jelement = new JsonParser().parse(jsonLine);
JsonElement jelement = new JsonParser().parse(jsonLine);
JsonObject  jobject = jelement.getAsJsonObject();
JsonObject  jobject = jelement.getAsJsonObject();
String result = jobject.get("result").toString();
String result = jobject.get("result").getAsString();
return result;
return result;
}
}
Line 1,451: Line 183:
       DefaultHttpClient client = new DefaultHttpClient();           
       DefaultHttpClient client = new DefaultHttpClient();           
          
          
       HttpPost post = new HttpPost("http://PATH_OF_YOUR_SERVER/index.php/admin/remotecontrol");
       HttpPost post = new HttpPost("https://PATH_OF_YOUR_SERVER/index.php/admin/remotecontrol");
       post.setHeader("Content-type", "application/json");
       post.setHeader("Content-type", "application/json");
       post.setEntity( new StringEntity("{\"method\": \"get_session_key\", \"params\": {\"username\": \"YOUR_USERNAME\", \"password\": \"YOUR_PASSWORD\" }, \"id\": 1}"));
       post.setEntity( new StringEntity("{\"method\": \"get_session_key\", \"params\": [\"YOUR_USERNAME\", \"YOUR_PASSWORD\" ], \"id\": 1}"));
       try {
       try {
         HttpResponse response = client.execute(post);
         HttpResponse response = client.execute(post);
Line 1,459: Line 191:
             HttpEntity entity = response.getEntity();
             HttpEntity entity = response.getEntity();
             String sessionKey = parse(EntityUtils.toString(entity));
             String sessionKey = parse(EntityUtils.toString(entity));
             post.setEntity( new StringEntity("{\"method\": \"list_groups\", \"params\": {\"sSessionKey \": "+sessionKey+", \"iSurveyID \": \"ID_SURVEY\" }, \"id\": 1}"));
             post.setEntity( new StringEntity("{\"method\": \"list_groups\", \"params\": [ \""+sessionKey+"\", \"ID_SURVEY\" ], \"id\": 1}"));
             response = client.execute(post);
             response = client.execute(post);
             if(response.getStatusLine().getStatusCode() == 200){
             if(response.getStatusLine().getStatusCode() == 200){
Line 1,476: Line 208:
</syntaxhighlight>
</syntaxhighlight>


=Python example=
== Python example and glue ==
<syntaxhighlight lang="python" enclose="div">
 
* [https://github.com/TaiSHiNet/lime-py-api LimeSurvey API - Python 2 glue]
* [https://github.com/lindsay-stevens/limesurveyrc2api LimeSurvey API - Basic client library in Python 3]. Includes tests. Listed on Pypi: pip install limesurveyrc2api
 
The following code runs with Python 2 and requires some adaptation to work with Python 3.
 
<syntaxhighlight lang="python">
import urllib
import urllib
import urllib2
import urllib2
Line 1,487: Line 225:
          
          
def get_session_key():
def get_session_key():
     req = urllib2.Request(url='http://myurl/index.php/admin/remotecontrol',\
     req = urllib2.Request(url='https://myurl/index.php/admin/remotecontrol',\
                           data='{\"method\":\"get_session_key\",\"params\":{\"username\":\"admin\",\"password\":\"mypassword\"},\"id\":1}')
                           data='{\"method\":\"get_session_key\",\"params\":[\"admin\",\"mypassword\"],\"id\":1}')
     req.add_header('content-type', 'application/json')
     req.add_header('content-type', 'application/json')
     req.add_header('connection', 'Keep-Alive')
     req.add_header('connection', 'Keep-Alive')
Line 1,502: Line 240:
def get_question_properties(skey,QuestionID):
def get_question_properties(skey,QuestionID):
     req = urllib2.Request(url='http://myurl/index.php/admin/remotecontrol',\
     req = urllib2.Request(url='https://myurl/index.php/admin/remotecontrol',\
                           data='{\"method\":\"get_question_properties\",\"params\":{\"sSessionKey\":\"'+skey+'\",\"iQuestionID\":'+QuestionID+',\
                           data='{\"method\":\"get_question_properties\",\"params\":[\"'+skey+'\",'+QuestionID
\"aQuestionSettings\":[\"gid\",\"type\",\"help\",\"language\",\"sid\",\"question_order\",\"question\",\"subquestions\"]},\"id\": 1}')
                                    +',[\"gid\",\"type\",\"help\",\"language\",\"sid\",\"question_order\",\"question\",\"subquestions\"]],\"id\": 1}')


     req.add_header('content-type', 'application/json')
     req.add_header('content-type', 'application/json')
Line 1,520: Line 258:
def release_session_key(relkey):
def release_session_key(relkey):
     req = urllib2.Request(url='http://myurl/index.php/admin/remotecontrol',\
     req = urllib2.Request(url='https://myurl/index.php/admin/remotecontrol',\
                           data='{\"method\":\"release_session_key\",\"params\":{\"sSessionKey\":\"'+relkey+'\"},\"id\":1}')
                           data='{\"method\":\"release_session_key\",\"params\":[\"'+relkey+'\"],\"id\":1}')
     req.add_header('content-type', 'application/json')
     req.add_header('content-type', 'application/json')
     req.add_header('connection', 'Keep-Alive')
     req.add_header('connection', 'Keep-Alive')
Line 1,536: Line 274:


def export_responses2(skey,sid):
def export_responses2(skey,sid):
     req = urllib2.Request(url='http://myurl/index.php/admin/remotecontrol',\
     req = urllib2.Request(url='https://myurl/index.php/admin/remotecontrol',\
                           data='{\"method\":\"export_responses\",\"params\":{\"sSessionKey\":\"'+skey+'\",\"iSurveyID\":\"'+sid+'\",\
                           data='{\"method\":\"export_responses\",\"params\":[\"'+skey+'\",\"'+sid+'\",\"csv\",\"de\",\"full\"],\
\"DocumentType\":\"csv\",\"sLanguageCode\":\"de\",\"sHeadingType\":\"full\"},\
"id\": 1}')
"id\": 1}')
     req.add_header('content-type', 'application/json')
     req.add_header('content-type', 'application/json')
Line 1,559: Line 296:
</syntaxhighlight>
</syntaxhighlight>


=JSON-RPC notes=
== NodeJS example ==
 
This script require request, you can include easily with the command
<source lang=bash>
npm install request
</source>
 
This is a example how to connect to limesurvey:
 
<source lang="javascript">
var request = require('request');
 
//******GLOBAL***************
var SESSIONKEY="";
var options = {
  url: "https://xxxxxxxxxxxxxxxx/index.php/admin/remotecontrol",
  method: "POST",
  headers: {
    'user-agent': 'Apache-HttpClient/4.2.2 (java 1.5)',
    'host': 'xxxxxxxxxxxxxxxx',
    'path': '/index.php/admin/remotecontrol',
    'connection': 'keep-alive',
    'content-type': 'application/json'
  }
};
 
//*******AUTHENTIFICATION*******
options.body = JSON.stringify({method:'get_session_key',params:['myusername','mypassword'],id:1});
 
request(options, function(error, response, body){
  if (!error && response.statusCode == 200) {
      body = JSON.parse(body);
 
    //*********KEEP THE KEY********* 
    if(SESSIONKEY==="") {
      console.log("NEW KEY -->"+body.result);
      SESSIONKEY=body.result;
      nextFonction();
    }
  }
  else console.log("ERROR -->"+body); 
});
 
</source>
 
== R example and helper ==
 
The easiest way to use lsrc2 is by means of the limer package, See https://github.com/cloudyr/limer
 
Example of usage of this client
<source lang=R>
# first limer (check version: must be recent) must be installed
if(!require("devtools")) {
  install.packages("devtools")
  library("devtools")
}
install_github("cloudyr/limer")
#############################################################
 
library(limer)
 
#change the next options (website, user, password)
options
(lime_api = 'https://www.XXX.nl/index.php/admin/remotecontrol')
options(lime_username = 'user')
options(lime_password = 'password')
#############################################################
 
 
# first get a session access key
get_session_key()
 
# list all surveys. A dataframe is returned
survey_df<-call_limer(method='list_surveys')
print(survey_df)
#    sid          surveyls_title startdate            expires active
#1  999999  XXXX              NA 2016-03-08 15:20:30      Y
#2  999998  XXXX              NA  <NA>      Y
 
#Read the data of the first survey (sid=999999) into a data.frame.
#Notice that the default sLanguageCode = en, so maybe you have to
#specify another language (here: All languages)
data<- get_responses(iSurveyID= 999999, sLanguageCode= '', sResponseType='short')
       
</source>
 
== C# (Copy & Paste from Forum) ==
 
https://www.limesurvey.org/forum/development/99633-c-client-for-ls-remotecontrol2
 
I have written a small json-rpc client in c#. It is a small one but enough for my purposes. You can use it in your wiki as example or maybe it helps here other people.
It is tested and works in my environment but it is possible that i havent found all bugs.
You need from nuget package manager Newtonsoft JSON.
 
RPCclient.cs
<source lang="c#">
using System;
using System.IO;
using System.Net;
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace JsonRPCclient {
  public class JsonRPCclient {
    private int id = 0;
    /// <summary>
    /// Set JSON-RPC webservice URL
    /// </summary>
    public string URL { set; get; }
    /// <summary>
    /// Set JSON-RPC method
    /// </summary>
    public string Method { set; get; }
    /// <summary>
    /// Add JSON-RPC params
    /// </summary>
    public JObject Parameters { set; get; }
    /// <summary>
    /// Results of the request
    /// </summary>
    public JsonRPCresponse Response { set; get; }
    /// <summary>
    /// Create a new object of RPCclient
    /// </summary>
    public JsonRPCclient() {
      Parameters = new JObject();
      Response = null;
    }
    /// <summary>
    /// Create a new object of RPCclient
    /// </summary>
    /// <param name="URL"></param>
    public JsonRPCclient(string URL) {
      this.URL = URL;
      Parameters = new JObject();
      Response = null;
    }
    /// <summary>
    /// POST the request and returns server response
    /// </summary>
    /// <returns></returns>
    public string Post() {
      try {
        JObject jobject = new JObject();
        jobject.Add(new JProperty("jsonrpc", "2.0"));
        jobject.Add(new JProperty("id", ++id));
        jobject.Add(new JProperty("method", Method));
        jobject.Add(new JProperty("params", Parameters));
        string PostData = JsonConvert.SerializeObject(jobject);
        UTF8Encoding encoding = new UTF8Encoding();
        byte[] bytes = encoding.GetBytes(PostData);
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
        request.Method = "POST";
        request.ContentType = "application/json";
        request.KeepAlive = true;
        request.ContentLength = bytes.Length;
        Stream writeStream = request.GetRequestStream();
        writeStream.Write(bytes, 0, bytes.Length);
        writeStream.Close();
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        Stream responseStream = response.GetResponseStream();
        StreamReader readStream = new StreamReader(responseStream, Encoding.UTF8);
        Response = new JsonRPCresponse();
        Response = JsonConvert.DeserializeObject<JsonRPCresponse>(readStream.ReadToEnd());
        Response.StatusCode = response.StatusCode;
        return Response.ToString();
      }
      catch (Exception e) {
        return e.ToString();
      }
    }
    public void ClearParameters() {
      this.Parameters = new JObject();
    }
  }
  public class JsonRPCresponse {
    public int id { set; get; }
    public object result { set; get; }
    public string error { set; get; }
    public HttpStatusCode StatusCode { set; get; }
    public JsonRPCresponse() { }
    public override string ToString() {
      return "{\"id\":" + id.ToString() + ",\"result\":\"" + result.ToString() + "\",\"error\":" + error + ((String.IsNullOrEmpty(error)) ? "null" : "\"" + error + "\"") + "}";
    }
  }
}
</source>
 
programm.cs
<source lang="c#">
      string Baseurl = "http://localhost/limesurvey/index.php?r=admin/remotecontrol";
      JsonRPCclient client = new JsonRPCclient(Baseurl);
      client.Method = "get_session_key";
      client.Parameters.Add("username", "admin");
      client.Parameters.Add("password", "mypassword");
      client.Post();
      string SessionKey = client.Response.result.ToString();
      client.ClearParameters();
      if(client.Response.StatusCode == System.Net.HttpStatusCode.OK){
        client.Method = "import_survey";
        client.Parameters.Add("sSessionKey", SessionKey);
        client.Parameters.Add("sImportData", Base64Encode(yourImportDataString));
        client.Parameters.Add("sImportDataType", "lss");
        //client.Parameters.Add("sNewSurveyName", "test");
        //client.Parameters.Add("DestSurveyID", 1);
        client.Post();
      }
      client.ClearParameters();
      Console.WriteLine("new survey id:" + client.Response.result.ToString());
      Console.ReadLine();
</source>
 
 
== VBA for Excel ==
 
To ‘automaticaly’ export the answers of a survey to an Excel sheet you can use this code.
 
Source: https://www.limesurvey.org/community/forums/development/120876-vba-for-remotecontrol2-json-rpc
 
<source lang="vb">
' -----------------------------------------------------------------------
' JSON RPC CONNECTIVITY SETTINGS
' -----------------------------------------------------------------------
' This file will contain the settings needed to access json RPC with vba.
'
' This VBA code use two different modules:
' VBA JSON tools: https://github.com/VBA-tools/VBA-JSON
' Base64 Deconding: http://www.vbforums.com/showthread.php?379072-VB-Fast-Base64-Encoding-and-Decoding&p=2539878&viewfull=1#post2539878
'
' I used the script made by vkuzmin as a base:
' https://www.limesurvey.org/community/forums/can-i-do-this-with-limesurvey/114846-export-answers-to-excel-in-semi-realtime
'
Sub export_limesurvey()
Dim key As String
Dim limeuser As String, limepass As String, limeurl As String, URL As String
Dim jsonText As String, jsonObject As Object
Dim SurveyID As String, DocumentType As String
Dim export64 As String, export64Decoded As String
limeurl = "https://www.website.com/index.php"
limeuser = "user"
limepass = "pasword"
SurveyID = "id"
DocumentType = "csv"
'Clear page
Cells.Clear
'Initalization
Set objHTTP = CreateObject("WinHttp.WinHttpRequest.5.1")
URL = limeurl + "/admin/remotecontrol"
objHTTP.Open "POST", URL, False
objHTTP.setRequestHeader "User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)"
objHTTP.setRequestHeader "Content-type", "application/json"
'Get key
sendtext = "{""method"":""get_session_key"",""params"": [""" + limeuser + """,""" + limepass + """],""id"": 1}"
objHTTP.Send (sendtext)
jsonText = objHTTP.responseText
Set jsonObject = JsonConverter.ParseJson(jsonText)
key = jsonObject("result")
'Export answers
sendtext = "{""method"":""export_responses"",""params"": [""" + key + """,""" + SurveyID + """,""" + DocumentType + """],""id"": 1}"
objHTTP.Send (sendtext)
jsonText = objHTTP.responseText
Set jsonObject = JsonConverter.ParseJson(jsonText)
export64 = jsonObject("result")
'Decode answers
export64Decoded = Decode64(export64)
'Close session
sendtext = "{""method"":""release_session_key"",""params"": [""" + key + """],""id"": 1}"
objHTTP.Send (sendtext)
'Divide the respond in multiple lines, otherwise evrything is in one cell
s = export64Decoded
i = 0
While Split(s, Chr(13) + Chr(10))(i) <> ""
  Cells(i + 1, 1) = Split(s, Chr(13) + Chr(10))(i)
  i = i + 1
Wend
'Convert CSV
Columns("A:A").TextToColumns Destination:=Range("A1"), DataType:=xlDelimited, _
        TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=False, _
        Semicolon:=True, Comma:=False, Space:=False, Other:=False, TrailingMinusNumbers:=True
Cells.WrapText = False
End Sub
</source>
 
 
= JSON-RPC notes =


The content-type of the HTTP request must be application/json.  Most formatting errors or a failure to set the content-type header will result in a null response from the server (not a JSON response).  Below is an example of a valid request and response pair.
The content-type of the HTTP request '''must be application/json'''.  Most formatting errors are a failure to set the content-type header.  This will result in a null response from the server (not a JSON response).  Below is an example of a valid request and response pair.


<syntaxhighlight lang="php" enclose="div">Request:
<syntaxhighlight lang="php">Request:


 HTTP headers:
 HTTP headers:
Line 1,573: Line 630:
   host=mylimesurveyhost.com
   host=mylimesurveyhost.com


   content-length=65
   content-length=67


   user-agent=Apache-HttpClient/4.2.2 (java 1.5)
   user-agent=Apache-HttpClient/4.2.2 (java 1.5)
Line 1,579: Line 636:
 Post body:
 Post body:


   {"method":"get_session_key","params":{"username":"admin","password":"mypassword"},"id":1}
   {"method":"get_session_key","params":["admin","mypassword"],"id":1}


Response body:
Response body:


 {"id":1,"result":"6htqat38fyr4v7iu72nqgv7xgavkvfcz","error":null}</syntaxhighlight>
 {"id":1,"result":"6htqat38fyr4v7iu72nqgv7xgavkvfcz","error":null}</syntaxhighlight>

Latest revision as of 15:08, 16 February 2022

Introduction

LimeSurvey RemoteControl 2 is a XML-RPC/JSON-RPC based web service available in LimeSurvey 2.0 or more recent which offers various API functions.

LSRC2 makes it possible for developers to control specific functionality of LimeSurvey from any other application, without being restricted to PHP as a programming language.

The following features are planned:

  • start a predefined survey (change titles and things)
  • add predefined groups or questions
  • activate the survey, restrict it to start and endtime
  • make it closed,
  • add participant data/tokens when you need them
  • return the unused tokens to the main application
  • get a fieldmap for a survey,
  • invite or remind the participants of your survey

...and much more

Requirements

  • libXML installed

Setup

How to configure LSRC2

In a default LimeSurvey installation LSRC2 is disabled. In order to use LSRC2 you must first enable the service, and then adjust the settings to suit your needs. To enable LSRC2 login to the LimeSurvey administration, go to Global settings, choose the tab 'Interfaces' and select one of the two RPC services (XML-RPC or JSON-RPC) service.


  Do not forget to activate the LimeSurvey API first! To do this, access your global configuration, click on Interfaces and enable the API setting.


Security

LSRC2 uses the same security measures as the normal administration login. That means that the permission set of the used username and password is the same as if you would login in the administration with that user/password. Also LSRC2 is protected against brute-force password cracking - like the normal administration login.

How to use LSRC2

The LSRC2 URL are shown on global settings, it was adapted to your current configuration.

LSRC2 fully complies to the XML-RPC specification and JSON-RPC version 1 specifications. We recommend in general to use JSON-RPC because it is well tested and has a much smaller footprint than XML-RPC.

LSRC2 offers a lot of functions. Please check the automatically generated API Documentation. LSRC2 offers the following functions:

Sessions

get_session_key

Using this function you can create a new XML/JSON-RPC session key. This is mandatory for all following LSRC2 function calls.

function get_session_key(string $username, string $password, string $plugin = 'Authdb')
Parameter Description
username The username used for connexion
password The password used for connexion
plugin (New in 3.2.0 ) The Auth plugin to be used

Return on success: (string) session key.

Return on error: for protocol-level errors (invalid format etc), an error message. For invalid username and password, returns a null error and the result body contains a 'status' name-value pair with the error message.

release_session_key

Using this function you can close a previously opened XML-RPC/JSON-RPC session.

function release_session_key(string $sSessionKey)
Parameter Description
sSessionKey Auth credentials

Return: Always 'OK' (string)

List of functions

All functions including descriptions can be found at our developers RemoteControl functions API page.


Also, you can publish your API (check out global settings) and look at it directly.


  The parameter structure uses arrays of values - you *must* send the values in the API expected order (see jsonrpc specification).


Example and helper

PHP Example

To include JSON-RPC in your application, you can write an application using the light-weight jsonRPCClient from the jsonrpcphp Github repository. The library can also get included by composer calling

composer require weberhofer/jsonrpcphp

or by inclusion of the following lines in your composer.json file:

{
    "require": {
        "weberhofer/jsonrpcphp": "~2"
    }
}

This is an example how to connect to limesurvey:

<?php

// without composer this line can be used
// require_once 'path/to/your/rpcclient/jsonRPCClient.php';
// with composer support just add the autoloader
include_once 'vendor/autoload.php';

define( 'LS_RPCURL', 'https://localhost/limesurvey/admin/remotecontrol');  // adjust this one to your actual Remote Control URL
define( 'LS_USER', 'rpcuser' );
define( 'LS_PASSWORD', 'mypassword' );

// the survey to process
$survey_id=374699;

// instantiate a new client
$myJSONRPCClient = new \org\jsonrpcphp\JsonRPCClient( LS_RPCURL );

// receive session key
$sessionKey= $myJSONRPCClient->get_session_key( LS_USER, LS_PASSWORD );

// receive surveys list current user can read
$groups = $myJSONRPCClient->list_surveys( $sessionKey );
print_r($groups, null );

// release the session key
$myJSONRPCClient->release_session_key( $sessionKey );

See a snippet example of list_surveys

JAVA example

To decode and code your json calls you can use the library gson as you can see in the following example:

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

public class TestHttpClient {
	
    public static String parse(String jsonLine) {
	 JsonElement jelement = new JsonParser().parse(jsonLine);
	 JsonObject  jobject = jelement.getAsJsonObject();
	 String result = jobject.get("result").getAsString();
	 return result;
	}
	
	
    public static void main(String[] args) throws UnsupportedEncodingException {
      DefaultHttpClient client = new DefaultHttpClient();          
         
      HttpPost post = new HttpPost("https://PATH_OF_YOUR_SERVER/index.php/admin/remotecontrol");
      post.setHeader("Content-type", "application/json");
      post.setEntity( new StringEntity("{\"method\": \"get_session_key\", \"params\": [\"YOUR_USERNAME\", \"YOUR_PASSWORD\" ], \"id\": 1}"));
      try {
        HttpResponse response = client.execute(post);
        if(response.getStatusLine().getStatusCode() == 200){
            HttpEntity entity = response.getEntity();
            String sessionKey = parse(EntityUtils.toString(entity));
            post.setEntity( new StringEntity("{\"method\": \"list_groups\", \"params\": [ \""+sessionKey+"\", \"ID_SURVEY\" ], \"id\": 1}"));
            response = client.execute(post);
            if(response.getStatusLine().getStatusCode() == 200){
                entity = response.getEntity();
                System.out.println(EntityUtils.toString(entity));
                }
           }
       
       
      } catch (IOException e) {
        e.printStackTrace();
      }
    }}

Python example and glue

The following code runs with Python 2 and requires some adaptation to work with Python 3.

import urllib
import urllib2
import json
import sys
# There is an generic json-rpc implemantation in Python but it dose not work for me in this case so I worte Some functions 


        
def get_session_key():
    req = urllib2.Request(url='https://myurl/index.php/admin/remotecontrol',\
                          data='{\"method\":\"get_session_key\",\"params\":[\"admin\",\"mypassword\"],\"id\":1}')
    req.add_header('content-type', 'application/json')
    req.add_header('connection', 'Keep-Alive')
    try:
        f = urllib2.urlopen(req)
        myretun = f.read()
        #print myretun
        j=json.loads(myretun)
        return j['result']
    except :
        e = sys.exc_info()[0]
        print ( "<p>Error: %s</p>" % e )
		
def get_question_properties(skey,QuestionID):
    req = urllib2.Request(url='https://myurl/index.php/admin/remotecontrol',\
                          data='{\"method\":\"get_question_properties\",\"params\":[\"'+skey+'\",'+QuestionID
                                    +',[\"gid\",\"type\",\"help\",\"language\",\"sid\",\"question_order\",\"question\",\"subquestions\"]],\"id\": 1}')

    req.add_header('content-type', 'application/json')
    req.add_header('connection', 'Keep-Alive')
    try:
        f = urllib2.urlopen(req)
        myretun = f.read()
        #print myretun
        j=json.loads(myretun)
        return j['result']
    except :
        e = sys.exc_info()[0]
        print ( "<p>Error: %s</p>" % e )

		
def release_session_key(relkey):
    req = urllib2.Request(url='https://myurl/index.php/admin/remotecontrol',\
                          data='{\"method\":\"release_session_key\",\"params\":[\"'+relkey+'\"],\"id\":1}')
    req.add_header('content-type', 'application/json')
    req.add_header('connection', 'Keep-Alive')
    try:
        f = urllib2.urlopen(req)
        myretun = f.read()
        #print myretun
        j=json.loads(myretun)
        return j['result']
    except :
        e = sys.exc_info()[0]
        print ( "<p>Error: %s</p>" % e )


def export_responses2(skey,sid):
    req = urllib2.Request(url='https://myurl/index.php/admin/remotecontrol',\
                          data='{\"method\":\"export_responses\",\"params\":[\"'+skey+'\",\"'+sid+'\",\"csv\",\"de\",\"full\"],\
"id\": 1}')
    req.add_header('content-type', 'application/json')
    req.add_header('connection', 'Keep-Alive')
    try:
        f = urllib2.urlopen(req)
        myretun = f.read()
        #print myretun
        j=json.loads(myretun)
        return j['result']
    except :
        e = sys.exc_info()[0]
        print ( "<p>Error: %s</p>" % e )		

		
mykey=get_session_key()
print export_responses2(mykey,'566237').decode('base64')
get_question_properties(mykey,'574')
print release_session_key(mykey)

NodeJS example

This script require request, you can include easily with the command

npm install request

This is a example how to connect to limesurvey:

var request = require('request');

//******GLOBAL***************
var SESSIONKEY="";
var options = {
  url: "https://xxxxxxxxxxxxxxxx/index.php/admin/remotecontrol",
  method: "POST",
  headers: {
    'user-agent': 'Apache-HttpClient/4.2.2 (java 1.5)',
    'host': 'xxxxxxxxxxxxxxxx',
    'path': '/index.php/admin/remotecontrol',
    'connection': 'keep-alive',
    'content-type': 'application/json'
  }
};

//*******AUTHENTIFICATION*******
options.body = JSON.stringify({method:'get_session_key',params:['myusername','mypassword'],id:1});

request(options, function(error, response, body){
  if (!error && response.statusCode == 200) {
      body = JSON.parse(body);

    //*********KEEP THE KEY*********  
    if(SESSIONKEY==="") {
      console.log("NEW KEY -->"+body.result);
      SESSIONKEY=body.result;
      nextFonction();
    } 
  }
  else console.log("ERROR -->"+body);  
});

R example and helper

The easiest way to use lsrc2 is by means of the limer package, See https://github.com/cloudyr/limer

Example of usage of this client

# first limer (check version: must be recent) must be installed
if(!require("devtools")) {
  install.packages("devtools")
  library("devtools")
}
install_github("cloudyr/limer")
#############################################################

library(limer)

#change the next options (website, user, password)
options
(lime_api = 'https://www.XXX.nl/index.php/admin/remotecontrol')
options(lime_username = 'user')
options(lime_password = 'password')
#############################################################


# first get a session access key
get_session_key()

# list all surveys. A dataframe is returned
survey_df<-call_limer(method='list_surveys')
print(survey_df)
#    sid           surveyls_title startdate             expires active
#1  999999  XXXX               NA 2016-03-08 15:20:30      Y
#2  999998  XXXX               NA   <NA>      Y

#Read the data of the first survey (sid=999999) into a data.frame. 
#Notice that the default sLanguageCode = en, so maybe you have to 
#specify another language (here: All languages)
data<- get_responses(iSurveyID= 999999, sLanguageCode= '', sResponseType='short')

C# (Copy & Paste from Forum)

https://www.limesurvey.org/forum/development/99633-c-client-for-ls-remotecontrol2

I have written a small json-rpc client in c#. It is a small one but enough for my purposes. You can use it in your wiki as example or maybe it helps here other people. It is tested and works in my environment but it is possible that i havent found all bugs. You need from nuget package manager Newtonsoft JSON.

RPCclient.cs

using System;
using System.IO;
using System.Net;
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
 
namespace JsonRPCclient {
 
  public class JsonRPCclient {
 
    private int id = 0;
    /// <summary>
    /// Set JSON-RPC webservice URL
    /// </summary>
    public string URL { set; get; }
    /// <summary>
    /// Set JSON-RPC method
    /// </summary>
    public string Method { set; get; }
    /// <summary>
    /// Add JSON-RPC params
    /// </summary>
    public JObject Parameters { set; get; }
 
    /// <summary>
    /// Results of the request
    /// </summary>
    public JsonRPCresponse Response { set; get; }
 
 
    /// <summary>
    /// Create a new object of RPCclient 
    /// </summary>
    public JsonRPCclient() {
      Parameters = new JObject();
      Response = null;
    }
 
    /// <summary>
    /// Create a new object of RPCclient
    /// </summary>
    /// <param name="URL"></param>
    public JsonRPCclient(string URL) {
      this.URL = URL;
      Parameters = new JObject();
      Response = null;
    }
 
    /// <summary>
    /// POST the request and returns server response
    /// </summary>
    /// <returns></returns>
    public string Post() {
      try {
        JObject jobject = new JObject();
        jobject.Add(new JProperty("jsonrpc", "2.0"));
        jobject.Add(new JProperty("id", ++id));
        jobject.Add(new JProperty("method", Method));
        jobject.Add(new JProperty("params", Parameters));
 
        string PostData = JsonConvert.SerializeObject(jobject);
        UTF8Encoding encoding = new UTF8Encoding();
        byte[] bytes = encoding.GetBytes(PostData);
 
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
        request.Method = "POST";
        request.ContentType = "application/json";
        request.KeepAlive = true;
        request.ContentLength = bytes.Length;
 
        Stream writeStream = request.GetRequestStream();
        writeStream.Write(bytes, 0, bytes.Length);
        writeStream.Close();
 
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        Stream responseStream = response.GetResponseStream();
        StreamReader readStream = new StreamReader(responseStream, Encoding.UTF8);
 
        Response = new JsonRPCresponse();
        Response = JsonConvert.DeserializeObject<JsonRPCresponse>(readStream.ReadToEnd());
        Response.StatusCode = response.StatusCode;
 
        return Response.ToString();
      }
      catch (Exception e) {
        return e.ToString();
      }
    }
 
    public void ClearParameters() {
      this.Parameters = new JObject();
    }
 
 
  }
 
  public class JsonRPCresponse {
    public int id { set; get; }
    public object result { set; get; }
    public string error { set; get; }
    public HttpStatusCode StatusCode { set; get; }
 
    public JsonRPCresponse() { }
 
    public override string ToString() {
      return "{\"id\":" + id.ToString() + ",\"result\":\"" + result.ToString() + "\",\"error\":" + error + ((String.IsNullOrEmpty(error)) ? "null" : "\"" + error + "\"") + "}";
    }
  }
 
}

programm.cs

      string Baseurl = "http://localhost/limesurvey/index.php?r=admin/remotecontrol";
      JsonRPCclient client = new JsonRPCclient(Baseurl);
      client.Method = "get_session_key";
      client.Parameters.Add("username", "admin");
      client.Parameters.Add("password", "mypassword");
      client.Post();
      string SessionKey = client.Response.result.ToString();
 
      client.ClearParameters();
 
      if(client.Response.StatusCode == System.Net.HttpStatusCode.OK){
        client.Method = "import_survey";
        client.Parameters.Add("sSessionKey", SessionKey);
        client.Parameters.Add("sImportData", Base64Encode(yourImportDataString));
        client.Parameters.Add("sImportDataType", "lss");
        //client.Parameters.Add("sNewSurveyName", "test");
        //client.Parameters.Add("DestSurveyID", 1);
        client.Post();
      }
 
      client.ClearParameters();
 
      Console.WriteLine("new survey id:" + client.Response.result.ToString());
      Console.ReadLine();


VBA for Excel

To ‘automaticaly’ export the answers of a survey to an Excel sheet you can use this code.

Source: https://www.limesurvey.org/community/forums/development/120876-vba-for-remotecontrol2-json-rpc

' -----------------------------------------------------------------------
' JSON RPC CONNECTIVITY SETTINGS
' -----------------------------------------------------------------------
' This file will contain the settings needed to access json RPC with vba.
'
' This VBA code use two different modules:
' VBA JSON tools: https://github.com/VBA-tools/VBA-JSON
' Base64 Deconding: http://www.vbforums.com/showthread.php?379072-VB-Fast-Base64-Encoding-and-Decoding&p=2539878&viewfull=1#post2539878
' 
' I used the script made by vkuzmin as a base:
' https://www.limesurvey.org/community/forums/can-i-do-this-with-limesurvey/114846-export-answers-to-excel-in-semi-realtime
' 
Sub export_limesurvey()
Dim key As String
Dim limeuser As String, limepass As String, limeurl As String, URL As String
Dim jsonText As String, jsonObject As Object
Dim SurveyID As String, DocumentType As String
Dim export64 As String, export64Decoded As String
 
limeurl = "https://www.website.com/index.php"
limeuser = "user"
limepass = "pasword"
SurveyID = "id"
DocumentType = "csv"
 
'Clear page
Cells.Clear
 
'Initalization
Set objHTTP = CreateObject("WinHttp.WinHttpRequest.5.1")
URL = limeurl + "/admin/remotecontrol"
objHTTP.Open "POST", URL, False
objHTTP.setRequestHeader "User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)"
objHTTP.setRequestHeader "Content-type", "application/json"
 
'Get key
sendtext = "{""method"":""get_session_key"",""params"": [""" + limeuser + """,""" + limepass + """],""id"": 1}"
objHTTP.Send (sendtext)
jsonText = objHTTP.responseText
Set jsonObject = JsonConverter.ParseJson(jsonText)
key = jsonObject("result")
 
'Export answers
sendtext = "{""method"":""export_responses"",""params"": [""" + key + """,""" + SurveyID + """,""" + DocumentType + """],""id"": 1}"
objHTTP.Send (sendtext)
jsonText = objHTTP.responseText
Set jsonObject = JsonConverter.ParseJson(jsonText)
export64 = jsonObject("result")
 
'Decode answers
export64Decoded = Decode64(export64)
 
'Close session
sendtext = "{""method"":""release_session_key"",""params"": [""" + key + """],""id"": 1}"
objHTTP.Send (sendtext)
 
'Divide the respond in multiple lines, otherwise evrything is in one cell
s = export64Decoded
i = 0
While Split(s, Chr(13) + Chr(10))(i) <> ""
   Cells(i + 1, 1) = Split(s, Chr(13) + Chr(10))(i)
   i = i + 1
Wend
 
'Convert CSV
Columns("A:A").TextToColumns Destination:=Range("A1"), DataType:=xlDelimited, _
        TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=False, _
        Semicolon:=True, Comma:=False, Space:=False, Other:=False, TrailingMinusNumbers:=True
 
Cells.WrapText = False
 
End Sub


JSON-RPC notes

The content-type of the HTTP request must be application/json.  Most formatting errors are a failure to set the content-type header. This will result in a null response from the server (not a JSON response).  Below is an example of a valid request and response pair.

Request:

 HTTP headers:

   content-type=application/json

   connection=Keep-Alive

   host=mylimesurveyhost.com

   content-length=67

   user-agent=Apache-HttpClient/4.2.2 (java 1.5)

 Post body:

   {"method":"get_session_key","params":["admin","mypassword"],"id":1}

Response body:

 {"id":1,"result":"6htqat38fyr4v7iu72nqgv7xgavkvfcz","error":null}