sharepoint
Servizi REST
Ricerca…
Osservazioni
URL endpoint del servizio REST
L'API di accesso client REST è stata introdotta per la prima volta in SharePoint 2010, ma è stata notevolmente ampliata in SharePoint 2013. L'API REST in SharePoint 2010 è accessibile tramite il servizio Web ListData all'indirizzo /_vti_bin/ListData.svc
. SharePoint 2013 ha introdotto gli /_api/lists/
e /_api/web
endpoint, che si comportano in modo leggermente diverso.
Gli URL degli endpoint sopra indicati devono essere preceduti da http://server/site
cui il server
rappresenta il nome del server e il site
rappresenta il nome o il percorso del sito specifico.
URL di esempio per ... | SharePoint 2010 | SharePoint 2013 |
---|---|---|
Recupero di una lista: | /_vti_bin/ListData.svc/ListName | /_api/lists('ListGuid') |
Recupero di un oggetto: | /_vti_bin/ListData.svc/ListName(1) | /_api/lists('ListGuid')/items(1) |
Recupero di un Web: | (nessun equivalente) | /_api/web |
Nonostante le differenze nell'accedere ad elenchi e voci di elenco, lavorare con questi risultati è molto simile in entrambe le versioni.
Si noti che il servizio ListData.svc
è ancora disponibile in SharePoint 2013 per compatibilità con le versioni precedenti.
Invio di richieste REST
Una richiesta REST può essere inviata tramite un XMLHttpRequest JavaScript nativo o tramite il costrutto wrapper jQuery AJAX.
Sintassi XMLHttpRequest
var xhr = new XMLHttpRequest();
xhr.open(verb, url, true);
xhr.setRequestHeader("Content-Type","application/json");
xhr.send(data);
jQuery AJAX Sintassi
$.ajax({
method: verb,
url: url,
headers: { "Content-Type":"application/json" },
data: data
});
Per ulteriori dettagli sull'invio di richieste tramite AJAX, consultare la documentazione JavaScript AJAX .
Lavorare con le liste
Ottenere elementi della lista
Questo esempio mostra come recuperare tutti gli elementi della lista e iterare attraverso di essi. Puoi usare il parametro top
per richiedere un certo numero di risultati. È inoltre possibile utilizzare il parametro select
per selezionare determinati campi ( $select=id, Title, uri
).
JavaScript
function GetListItems(){
$.ajax({
url: "../_api/web/lists/getbytitle('List Title')/items?$top=50"
contentType: "application/json;odata=verbose",
method: "GET",
headers: { "accept": "application/json;odata=verbose" },
success: function (data) {
$.each(data.d.results, function(index,item){
//use item to access the individual list item
console.log(item.Id);
});
},
error: function(error){
console.log(error);
}
});
}
Ottenere un singolo elemento della lista
JavaScript
function GetListItem(){
$.ajax({
url: "../_api/web/lists/getbytitle('List Title')/items(1)",
contentType: "application/json;odata=verbose",
method: "GET",
headers: { "accept": "application/json;odata=verbose" },
success: function (data) {
console.log(data.d.Id);
},
error: function(error){
console.log(error);
}
});
}
Ottieni elementi elenco con colonne di ricerca
A volte, potresti avere una struttura di lista simile a questa:
Tabella di elenco degli animali
Nome | genere | Descrizione |
---|---|---|
Titolo | String (testo) | Nome dell'animale |
Età | Numero | Quanti anni ha l'animale? |
Valore | Moneta | Valore dell'animale |
genere | Ricerca (tabella Tipi di animali) | Campo di ricerca (fornisce il menu a discesa delle scelte dalla tabella Tipi di animali) |
Tabella dei tipi di animali
Nome | genere | Descrizione |
---|---|---|
Titolo | String (testo) | Nome della specie / tipo di animale (ex maiale) |
NumLegs | Numero | Numero di zampe sull'animale |
Probabilmente non è l'esempio più serio ma il problema qui è ancora valido. Quando si utilizza la normale richiesta per recuperare i valori dall'elenco di SharePoint, per il Type
di animale, si otterrà solo un campo chiamato TypeId
nella risposta JSON. Al fine di espandere questi elementi in una sola chiamata AJAX, nei parametri URL sono richiesti alcuni extra markup.
Questo esempio si applica a più di semplici colonne di ricerca. Quando si utilizzano le colonne People/Groups
, sono essenzialmente solo ricerche, quindi è possibile estrarre facilmente elementi come Title
, EMail
e altri.
Codice di esempio
Nota importante : quando si definiscono i campi che si desidera recuperare dalle colonne di ricerca, è necessario inserire come prefisso il nome del campo con il nome del campo di ricerca nella tabella originale. Ad esempio, se si desidera recuperare l'attributo NumLegs
dalla colonna di ricerca, è necessario digitare Type/NumLegs
.
JavaScript
// webUrl: The url of the site (ex. https://www.contoso.com/sites/animals)
// listTitle: The name of the list you want to query
// selectFields: the specific fields you want to get back
// expandFields: the name of the fields that need to be pulled from lookup tables
// callback: the name of the callback function on success
function getItems(webUrl,listTitle,selectFields, expandFields, callback){
var endpointUrl = webUrl + "/_api/web/lists/getbytitle('" + listTitle + "')/items";
endpointUrl+= '?$select=' + selectFields.join(",");
endpointUrl+= '&$expand=' + expandFields.join(",");
return executeRequest(endpointUrl,'GET', callback);
}
function executeRequest(url,method,callback,headers,payload)
{
if (typeof headers == 'undefined'){
headers = {};
}
headers["Accept"] = "application/json;odata=verbose";
if(method == "POST") {
headers["X-RequestDigest"] = $("#__REQUESTDIGEST").val();
}
var ajaxOptions =
{
url: url,
type: method,
contentType: "application/json;odata=verbose",
headers: headers,
success: function (data) { callback(data) }
};
if(method == "POST") {
ajaxOptions.data = JSON.stringify(payload);
}
return $.ajax(ajaxOptions);
}
// Setup the ajax request by setting all of the arguments to the getItems function
function getAnimals() {
var url = "https://www.contoso.com/sites/animals";
var listTitle = "AnimalListing";
var selectFields = [
"Title",
"Age",
"Value",
"Type/Title",
"Type/NumLegs"
];
var expandFields = [
"Type/Title",
"Type/NumLegs"
];
getItems(url, listTitle, selectFields, expandFields, processAnimals);
}
// Callback function
// data: returns the data given by SharePoint
function processAnimals(data) {
console.log(data);
// Process data here
}
// Start the entire process
getAnimals();
Aggiunta di selezioni a un campo di ricerca multivalore
In questo esempio si presuppone che la colonna di ricerca sia denominata MultiLookupColumnName
e che si desideri impostare il campo di ricerca multipla per cercare gli elementi con ID 1 e 2.
Utilizzando jQuery AJAX
var listName = "YourListName";
var lookupList = "LookupListName";
var idOfItemToUpdate = 1;
var url = "/server/site/_vti_bin/ListData.svc/"+listName+"("+idOfItemToUpdate+")";
var data = JSON.stringify({
MultiLookupColumnName:[
{__metadata:{uri:"http://yoursiteurl/_vti_bin/ListData.svc/"+lookupList+"(1)"}},
{__metadata:{uri:"http://yoursiteurl/_vti_bin/ListData.svc/"+lookupList+"(2)"}}
]
});
$.ajax({
method: 'POST',
url: url,
contentType: 'application/json',
headers: {
"X-HTTP-Method" : "MERGE",
"If-Match" : "*"
},
data: data
});
var listGuid = "id-of-list-to-update"; // use list GUID here
var lookupGuid = "id-of-lookup-list"; // use lookup list GUID here
var idOfItemToUpdate = 1;
var url = "/server/site/_api/lists('"+ listGuid + "')/items("+ idOfItemToUpdate + ")";
var data = JSON.stringify({
MultiLookupColumnName:[
{__metadata:{uri:"http://yoursiteurl/_api/lists('" + lookupGuid + "')/items(1)"}},
{__metadata:{uri:"http://yoursiteurl/_api/lists('" + lookupGuid + "')/items(2)"}}
]
});
$.ajax({
method: 'POST',
url: url,
contentType: 'application/json',
headers: {
"X-HTTP-Method" : "MERGE",
"If-Match" : "*"
},
data: data
});
Utilizzando XMLHttpRequest
var listName = "YourListName";
var lookupList = "LookupListName";
var idOfItemToUpdate = 1;
var url = "/server/site/_vti_bin/ListData.svc/YourListName("+idOfItemToUpdate+")";
var data = JSON.stringify({
MultiLookupColumnName:[
{__metadata:{uri:"http://yoursiteurl/_vti_bin/ListData.svc/"+lookupList+"(1)"}},
{__metadata:{uri:"http://yoursiteurl/_vti_bin/ListData.svc/"+lookupList+"(2)"}}
]
});
var xhr = new XMLHttpRequest();
xhr.open("POST",url,true);
xhr.setRequestHeader("X-HTTP-Method", "MERGE");
xhr.setRequestHeader("If-Match", "*");
xhr.setRequestHeader("Content-Type","application/json");
xhr.send(data);
var listGuid = "id-of-list-to-update";
var lookupGuid = "id-of-lookup-list";
var idOfItemToUpdate = 1;
var url = "/server/site/_api/lists('"+ listGuid + "')/items("+ idOfItemToUpdate + ")";
var data = JSON.stringify({
MultiLookupColumnName:[
{__metadata:{uri:"http://yoursiteurl/_api/lists('" + lookupGuid + "')/items(1)"}},
{__metadata:{uri:"http://yoursiteurl/_api/lists('" + lookupGuid + "')/items(2)"}}
]
});
var xhr = new XMLHttpRequest();
xhr.open("POST",url,true);
xhr.setRequestHeader("X-HTTP-Method", "MERGE");
xhr.setRequestHeader("If-Match", "*");
xhr.setRequestHeader("Content-Type","application/json");
xhr.send(data);
Elementi di elenco di paging restituiti da una query
Per simulare il paging usando REST puoi fare quanto segue:
Usa il parametro
$skip=n
per saltare le primen
voci in base al parametro$orderby
Usa il parametro
$top=n
per restituire le primen
voci in base ai parametri$orderby
e$skip
.
var endpointUrl = "/_api/lists('guid')/items"; // SP2010: "/_vti_bin/ListData.svc/ListName";
$.getJSON(
endpointUrl + "?$orderby=Id&$top=1000",
function(data){
processData(data); // you can do something with the results here
var count = data.d.results.length;
getNextBatch(count, processData, onComplete); // fetch next page
}
);
function getNextBatch(totalSoFar, processResults, onCompleteCallback){
$.getJSON(
endpointUrl + "?$orderby=Id&$skip="+totalSoFar+"&$top=1000",
function(data){
var count = data.d.results.length;
if(count > 0){
processResults(data); // do something with results
getNextBatch(totalSoFar+count, callback); // fetch next page
}else{
onCompleteCallback();
}
}
);
}
Recupera un ID dell'elemento appena creato nell'elenco di SharePoint
Questo esempio mostra come recuperare un ID di un elemento appena creato utilizzando l'API REST di SharePoint.
Nota :
listName : questa variabile contiene il nome del tuo elenco.
newItemBody - Questo sarà il corpo della richiesta per l'aggiunta di un nuovo elemento nell'elenco.
es. var newItemBody = {__metadata: {'type': 'SP.Data.MyListNameItem'}, Titolo: 'Some title value'};
function CreateListItemWithDetails(listName, newItemBody) {
var item = newItemBody;
return $.ajax({
url: _spPageContextInfo.siteAbsoluteUrl + "/_api/web/lists/getbytitle('" + listName + "')/items",
type: "POST",
contentType: "application/json;odata=verbose",
data: JSON.stringify(item),
headers: {
"Accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"content-Type": "application/json;odata=verbose"
}
});
}
CreateListItemWithDetails(listName, newItemBody)
.then(function(data){
//success callback
var NewlyCreatedItemId = data.d.ID;
}, function(data){
//failure callback
});
Come eseguire le operazioni CRUD utilizzando l'interfaccia REST di SharePoint 2010
Creare
Per eseguire un'operazione di CREAZIONE tramite REST, è necessario eseguire le seguenti azioni:
Crea una richiesta HTTP usando il verbo POST
. Utilizzare l'URL del servizio dell'elenco a cui si desidera aggiungere un'entità come destinazione per il POST. Imposta il tipo di contenuto su application/json
. Serializzare gli oggetti JSON che rappresentano i nuovi elementi dell'elenco come una stringa e aggiungere questo valore all'esempio JavaScript del corpo della richiesta:
function createListItem(webUrl,listName, itemProperties, success, failure) {
$.ajax({
url: webUrl + "/_vti_bin/listdata.svc/" + listName,
type: "POST",
processData: false,
contentType: "application/json;odata=verbose",
data: JSON.stringify(itemProperties),
headers: {
"Accept": "application/json;odata=verbose"
},
success: function (data) {
success(data.d);
},
error: function (data) {
failure(data.responseJSON.error);
}
});
}
uso
var taskProperties = {
'TaskName': 'Order Approval',
'AssignedToId': 12
};
createListItem('https://contoso.sharepoint.com/project/','Tasks',taskProperties,function(task){
console.log('Task' + task.TaskName + ' has been created');
},
function(error){
console.log(JSON.stringify(error));
}
);
Leggere
Per eseguire un'operazione di lettura tramite REST, è necessario eseguire le seguenti azioni:
Creare una richiesta HTTP usando il verbo GET
. Utilizzare l'URL del servizio dell'elemento di elenco a cui si desidera aggiungere un'entità come destinazione per GET. Imposta il tipo di contenuto su application/json
. Esempio di JavaScript:
function getListItemById(webUrl,listName, itemId, success, failure) {
var url = webUrl + "/_vti_bin/listdata.svc/" + listName + "(" + itemId + ")";
$.ajax({
url: url,
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
success(data.d);
},
error: function (data) {
failure(data.responseJSON.error);
}
});
}
uso
getListItemById('https://contoso.sharepoint.com/project/','Tasks',2,function(taskItem){
console.log(taskItem.TaskName);
},
function(error){
console.log(JSON.stringify(error));
}
);
Aggiornare
Per aggiornare un'entità esistente, è necessario eseguire le seguenti azioni:
Crea una richiesta HTTP usando il verbo POST
. Aggiungi un'intestazione del X-HTTP-Method
con un valore di MERGE
. Utilizzare l'URL del servizio dell'elemento dell'elenco che si desidera aggiornare come destinazione per l'intestazione POST Aggiungi un If-Match
con un valore dell'ETag originale dell'entità o *. Esempio di JavaScript:
function updateListItem(webUrl,listName,itemId,itemProperties,success, failure)
{
getListItemById(webUrl,listName,itemId,function(item){
$.ajax({
type: 'POST',
url: item.__metadata.uri,
contentType: 'application/json',
processData: false,
headers: {
"Accept": "application/json;odata=verbose",
"X-HTTP-Method": "MERGE",
"If-Match": item.__metadata.etag
},
data: Sys.Serialization.JavaScriptSerializer.serialize(itemProperties),
success: function (data) {
success(data);
},
error: function (data) {
failure(data);
}
});
},
function(error){
failure(error);
});
}
uso
var taskProperties = {
'TaskName': 'Approval',
'AssignedToId': 12
};
updateListItem('https://contoso.sharepoint.com/project/','Tasks',2,taskProperties,function(item){
console.log('Task has been updated');
},
function(error){
console.log(JSON.stringify(error));
}
);
Elimina
Per eliminare un'entità, è necessario eseguire le seguenti azioni:
Crea una richiesta HTTP usando il verbo POST
. Aggiungi un'intestazione del X-HTTP-Method
con un valore di DELETE
. Utilizza l'URL del servizio dell'elemento dell'elenco che desideri aggiornare come destinazione per l'intestazione POST Aggiungi un If-Match
con un valore dell'ETag originale dell'entità. Esempio di JavaScript:
function deleteListItem(webUrl, listName, itemId, success, failure) {
getListItemById(webUrl,listName,itemId,function(item){
$.ajax({
url: item.__metadata.uri,
type: "POST",
headers: {
"Accept": "application/json;odata=verbose",
"X-Http-Method": "DELETE",
"If-Match": item.__metadata.etag
},
success: function (data) {
success();
},
error: function (data) {
failure(data.responseJSON.error);
}
});
},
function (error) {
failure(error);
});
}
uso
deleteListItem('https://contoso.sharepoint.com/project/','Tasks',3,function(){
console.log('Task has been deleted');
},
function(error){
console.log(JSON.stringify(error));
}
);