Completar operaciones básicas con puntos de conexión REST de SharePointComplete basic operations using SharePoint REST endpoints

You can perform basic create, read, update, and delete (CRUD) operations by using the Representational State Transfer (REST) interface provided by SharePoint. The REST interface exposes all the SharePoint entities and operations that are available in the other SharePoint client APIs. One advantage of using REST is that you don't have to add references to any SharePoint libraries or client assemblies. Instead, you make HTTP requests to the appropriate endpoints to retrieve or update SharePoint entities, such as webs, lists, and list items.You can perform basic create, read, update, and delete (CRUD) operations by using the Representational State Transfer (REST) interface provided by SharePoint. The REST interface exposes all the SharePoint entities and operations that are available in the other SharePoint client APIs. One advantage of using REST is that you don't have to add references to any SharePoint libraries or client assemblies. Instead, you make HTTP requests to the appropriate endpoints to retrieve or update SharePoint entities, such as webs, lists, and list items.

Para obtener una introducción completa a la interfaz de REST de SharePoint y su arquitectura, vea Introducción al servicio REST para SharePoint.For an introduction to the SharePoint REST interface and its architecture, see Get to know the SharePoint REST service.

Para obtener información sobre cómo se trabaja con las entidades de SharePoint principales, vea Trabajar con listas y elementos de lista con REST y Trabajar con carpetas y archivos con REST.For information about how to work with core SharePoint entities, see Working with lists and list items with REST and Working with folders and files with REST.

Para obtener un ejemplo de cómo ejecutar varias operaciones de este tipo en el contexto de una aplicación web ASP.NET escrita en C#, vea SharePoint-Add-in-REST-OData-BasicDataOperations.For a sample that shows you how to do many of these operations in the context of an ASP.NET web application written in C#, see SharePoint-Add-in-REST-OData-BasicDataOperations.

Para obtener información sobre los conjuntos de API disponibles en la plataforma de SharePoint, vea Choose the right API set in SharePoint (Elegir el conjunto de API correcto en SharePoint).For information about the sets of APIs available on the SharePoint platform, see Choose the right API set in SharePoint.

Para obtener información sobre cómo usar las otras API cliente, vea lo siguiente:For information about how to use the other client APIs, see:

Operaciones HTTP en servicios REST de SharePointHTTP operations in SharePoint REST services

The endpoints in the SharePoint REST service correspond to the types and members in the SharePoint client object models. By using HTTP requests, you can use these REST endpoints to perform typical CRUD (Create, Read, Update, and Delete) operations against SharePoint entities, such as lists and sites.The endpoints in the SharePoint REST service correspond to the types and members in the SharePoint client object models. By using HTTP requests, you can use these REST endpoints to perform typical CRUD (Create, Read, Update, and Delete) operations against SharePoint entities, such as lists and sites.

Normalmente, los puntos de conexión que representan operaciones de lectura se asignan a comandos GET HTTP. Los puntos de conexión que representan operaciones de creación se asignan a comandos POST HTTP, y los puntos de conexión que representan tareas de actualización o inserción se asignan a comandos PUT HTTP.Typically, endpoints that represent Read operations map to HTTP GET commands, endpoints that represent create operations map to HTTP POST commands, and endpoints that represent update or insert operations map to HTTP PUT commands.

En SharePoint, use POST para crear entidades tales como listas y sitios. El servicio REST de SharePoint admite el envío de comandos POST que incluyen definiciones de objetos a extremos que representan colecciones. Por ejemplo, podría enviar un comando POST que incluyera una nueva definición de objetos de lista en ATOM a la siguiente dirección URL para crear una lista de SharePoint:In SharePoint, use POST to create entities such as lists and sites. The SharePoint REST service supports sending POST commands that include object definitions to endpoints that represent collections. For example, you could send a POST command that included a new list object definition in ATOM to the following URL, to create a SharePoint list:

http://<site url>/_api/web/lists

Para tareas POST, toda propiedad innecesaria se establece en sus valores predeterminados. Si trata de establecer una propiedad de solo lectura como parte de una tarea POST, el servicio devuelve una excepción.For POST operations, any properties that are not required are set to their default values. If you attempt to set a read-only property as part of a POST operation, the service returns an exception.

Use operaciones PUT y MERGE para actualizar objetos de SharePoint existentes. Los extremos de servicios que representan una operación set de propiedades de objeto admiten tanto solicitudes PUT como solicitudes MERGE. En el caso de las solicitudes MERGE, configurar las propiedades es opcional, de manera que aquellas que no defina explícitamente retendrán la propiedad actual. En el caso de los comandos PUT, sin embargo, las propiedades que no se configuren explícitamente se establecerán en los valores predeterminados. Además, si no especifica todas las propiedades necesarias en actualizaciones de objeto cuando use comandos PUT de HTTP, el servicio REST devolverá una excepción.Use PUT and MERGE operations to update existing SharePoint objects. Any service endpoint that represents an object property set operation supports both PUT requests and MERGE requests. For MERGE requests, setting properties is optional; any properties that you do not explicitly set retain their current property. For PUT commands, however, any properties you do not explicitly set are set to their default properties. In addition, if you do not specify all required properties in object updates when using HTTP PUT commands, the REST service returns an exception.

Use el comando HTTP DELETE con la dirección URL específica del extremo para eliminar el objeto de SharePoint representado por ese extremo. En el caso de los objetos reciclables, como listas, archivos y elementos de lista, esto da como resultado una operación Recycle.Use the HTTP DELETE command against the specific endpoint URL to delete the SharePoint object represented by that endpoint. In the case of recyclable objects, such as lists, files, and list items, this results in a Recycle operation.

Lectura de datos con la interfaz de REST de SharePointReading data with the SharePoint REST interface

Para usar las capacidades de REST que están integradas en SharePoint, construya una solicitud RESTful HTTP usando el estándar OData, que corresponde a la API del modelo de objetos de cliente que quiere usar. Cada entidad de SharePoint se expone en un extremo del sitio de SharePoint de destino y sus metadatos se representan en formato XML o JSON. Puede efectuar las solicitudes HTTP en cualquier lenguaje, incluidos, entre otros, JavaScript y C#.To use the REST capabilities that are built into SharePoint, you construct a RESTful HTTP request, using the OData standard, which corresponds to the client object model API you want to use. Each SharePoint entity is exposed at an endpoint on the SharePoint site that you are targeting, and its metadata is represented in either XML or JSON format. You can make the HTTP requests in any language, including but not limited to JavaScript and C#.

To read information from a REST endpoint, you must know both the URL of the endpoint and the OData representation of the SharePoint entity that is exposed at that endpoint. For example, to retrieve all the lists in a specific SharePoint site, you would make a GET request to http://<site url>/_api/web/lists. You can navigate to this URL in your browser and see the XML that gets returned. When you make the request in code, you can specify whether to receive the OData representation of the lists in XML or JSON.To read information from a REST endpoint, you must know both the URL of the endpoint and the OData representation of the SharePoint entity that is exposed at that endpoint. For example, to retrieve all the lists in a specific SharePoint site, you would make a GET request to http://<site url>/_api/web/lists. You can navigate to this URL in your browser and see the XML that gets returned. When you make the request in code, you can specify whether to receive the OData representation of the lists in XML or JSON.

The following C# code demonstrates how to make this GET request that returns a JSON representation of all of a site's lists by using JQuery. It also assumes that you have a valid OAuth access token that is stored in the accessToken variable. You do not need the access token if you make this call from inside an add-in web, as you would in a SharePoint-hosted add-in. Note that you cannot obtain an access token from code that is running on a browser client. You must obtain the access token from code that is running on a server.The following C# code demonstrates how to make this GET request that returns a JSON representation of all of a site's lists by using JQuery. It also assumes that you have a valid OAuth access token that is stored in the accessToken variable. You do not need the access token if you make this call from inside an add-in web, as you would in a SharePoint-hosted add-in. Note that you cannot obtain an access token from code that is running on a browser client. You must obtain the access token from code that is running on a server.

Para obtener más información sobre cómo se puede obtener un token de acceso, vea Flujo de tokens de contexto de OAuth para complementos para SharePoint y Flujo de código de autenticación de OAuth para aplicaciones en SharePoint.For more information about how you can obtain an access token, see Context Token OAuth flow for SharePoint Add-ins and Authorization Code OAuth flow for SharePoint Add-ins.


HttpWebRequest endpointRequest =
  (HttpWebRequest)HttpWebRequest.Create(
  "http://<site url>/_api/web/lists");
endpointRequest.Method = "GET";
endpointRequest.Accept = "application/json;odata=verbose";
endpointRequest.Headers.Add("Authorization", 
  "Bearer " + accessToken);
HttpWebResponse endpointResponse =
  (HttpWebResponse)endpointRequest.GetResponse();


This request would look a little different if you are writing your add-in in JavaScript while using the SharePoint cross-domain library. In this case, you don't need to provide an access token.This request would look a little different if you are writing your add-in in JavaScript while using the SharePoint cross-domain library. In this case, you don't need to provide an access token.

The following code demonstrates how this request would look if you are using the cross-domain library and want to receive the OData representation of the lists as XML instead of JSON. (Because Atom is the default response format, you don't have to include an Accept header.) For more information about using the cross-domain library, see Access SharePoint data from add-ins using the cross-domain library.The following code demonstrates how this request would look if you are using the cross-domain library and want to receive the OData representation of the lists as XML instead of JSON. (Because Atom is the default response format, you don't have to include an Accept header.) For more information about using the cross-domain library, see Access SharePoint data from add-ins using the cross-domain library.

var executor = new SP.RequestExecutor(appweburl);
executor.executeAsync(
    {
        url:
            appweburl +
            "/_api/SP.AppContextSite(@target)/web/lists?@target='" +
            hostweburl + "'",
        method: "GET",
        success: successHandler,
        error: errorHandler
    }
);

El código del ejemplo siguiente muestra cómo solicitar una representación JSON de todas las listas de un sitio usando C#. Se presupone que el usuario tiene un token de acceso OAuth que se almacena en la variable accessToken.The code in the following example shows you how to request a JSON representation of all of the lists in a site by using C#. It assumes that you have an OAuth access token that you are storing in the accessToken variable.

HttpWebRequest endpointRequest = (HttpWebRequest)HttpWebRequest.Create(sharepointUrl.ToString() + "/_api/web/lists");
endpointRequest.Method = "GET";
endpointRequest.Accept = "application/json;odata=verbose";
endpointRequest.Headers.Add("Authorization", "Bearer " + accessToken);
HttpWebResponse endpointResponse = (HttpWebResponse)endpointRequest.GetResponse();


Obtener propiedades que no se devuelven con el recursoGetting properties that aren't returned with the resource

Muchos valores de propiedades se devuelven cuando se recupera un recurso, pero con algunas propiedades, se debe enviar una solicitud GET directamente al extremo de la propiedad. Esto suele ser así con las propiedades que representan entidades de SharePoint.Many property values are returned when you retrieve a resource, but for some properties, you have to send a GET request directly to the property endpoint. This is typical of properties that represent SharePoint entities.

El siguiente ejemplo muestra cómo obtener una propiedad anexando el nombre de la propiedad al extremo del recurso. El ejemplo obtiene el valor de la propiedad de Author de un recurso File.The following example shows how to get a property by appending the property name to the resource endpoint. The example gets the value of the Author property from a File resource.

http://<site url>/_api/web/getfilebyserverrelativeurl('/<folder name>/<file name>')/author

Para obtener los resultados en formato JSON, incluya un encabezado Accept establecido en "application/json;odata=verbose".To get the results in JSON format, include an Accept header set to "application/json;odata=verbose".

Escritura de datos mediante la interfaz de RESTWriting data by using the REST interface

Puede crear y actualizar entidades de SharePoint creando solicitudes RESTful HTTP en los extremos apropiados igual que cuando lee datos. No obstante, una de las diferencias clave es que se usa una solicitud POST. Cuando actualiza entidades, también pasa un método de solicitud HTTP PUT o MERGE agregando uno de estos términos a los encabezados de la solicitud como valor de la clave X-HTTP-Method. El método MERGE actualiza únicamente las propiedades de la entidad que especifica el usuario, mientras que el método PUT sustituye la entidad existente por otra nueva que se suministra en el cuerpo de POST. Use el método DELETE para eliminar la entidad. Si crea o actualiza una entidad, debe proporcionar una representación OData de la entidad que quiere crear o cambiar en el cuerpo de la solicitud HTTP.You can create and update SharePoint entities by constructing RESTful HTTP requests to the appropriate endpoints, just as you do when you're reading data. One key difference, however, is that you use a POST request. When you're updating entities, you also pass a PUT or MERGE HTTP request method by adding one of those terms to the headers of your request as the value of the X-HTTP-Method key. The MERGE method updates only the properties of the entity that you specify, while the PUT method replaces the existing entity with a new one that you supply in the body of the POST. Use the DELETE method to delete the entity. When you create or update an entity, you must provide an OData representation of the entity that you want to create or change in the body of your HTTP request.

Cuando cree, actualice o elimine entidades de SharePoint, es importante que tenga en cuenta que, si no usa OAuth para autorizar sus solicitudes, estas operaciones también necesitan el valor de resumen de formulario de solicitud del servidor como valor del encabezado X-RequestDigest. Puede recuperar este valor ejecutando una solicitud POST con un cuerpo vacío a http://<site url>/_api/contextinfo y extrayendo el valor del nodo d:FormDigestValue en el XML que el extremo contextinfo devuelve. En el siguiente ejemplo se ve una solicitud HTTP al extremo contextinfo de C#.Another important consideration when creating, updating, and deleting SharePoint entities is that if you aren't using OAuth to authorize your requests, these operations require the server's request form digest value as the value of the X-RequestDigest header. You can retrieve this value by making a POST request with an empty body to http://<site url>/_api/contextinfo and extracting the value of the d:FormDigestValue node in the XML that the contextinfo endpoint returns. The following example shows an HTTP request to the contextinfo endpoint in C#.


HttpWebRequest endpointRequest =
  (HttpWebRequest)HttpWebRequest.Create(
  "http://<site url>/_api/contextinfo");
endpointRequest.Method = "POST";
endpointRequest.Accept = "application/json;odata=verbose";
HttpWebResponse endpointResponse =
  (HttpWebResponse)endpointRequest.GetResponse();


Si usa el flujo de autorización y autenticación descrito en Autorización y autenticación de complementos de SharePoint, no necesita incluir el resumen de solicitud en sus solicitudes.If you're using the authentication and authorization flow described in Authorization and authentication of SharePoint Add-ins, you don't need to include the request digest in your requests.

Si usa la biblioteca entre dominios de JavaScript, SP.RequestExecutor controla la obtención y el envío del valor implícito del formulario.If you're using the JavaScript cross-domain library, SP.RequestExecutor handles getting and sending the form digest value for you.

If you're creating a SharePoint-hosted SharePoint Add-in, you don't have to make a separate HTTP request to retrieve the form digest value. Instead, you can retrieve the value in JavaScript code from the SharePoint page (if the page uses the default master page), as shown in the following example, which uses JQuery and creates a list.If you're creating a SharePoint-hosted SharePoint Add-in, you don't have to make a separate HTTP request to retrieve the form digest value. Instead, you can retrieve the value in JavaScript code from the SharePoint page (if the page uses the default master page), as shown in the following example, which uses JQuery and creates a list.

jQuery.ajax({
        url: "http://<site url>/_api/web/lists",
        type: "POST",
        data:  JSON.stringify({ '__metadata': { 'type': 'SP.List' }, 'AllowContentTypes': true,
 'BaseTemplate': 100, 'ContentTypesEnabled': true, 'Description': 'My list description', 'Title': 'Test' }
),
        headers: { 
            "accept": "application/json;odata=verbose",
            "content-type": "application/json;odata=verbose",
            "content-length": <length of post body>,
            "X-RequestDigest": $("#__REQUESTDIGEST").val()
        },
        success: doSuccess,
        error: doError
});


En el ejemplo siguiente se muestra cómo actualizar la lista que se creó en el ejemplo anterior. El ejemplo cambia el título de la lista, usa JQuery y presupone que esta operación se está ejecutando en un complemento hospedado en SharePoint.The following example shows how to update the list that is created in the previous example. The example changes the title of the list, uses JQuery, and assumes that you are doing this operation in a SharePoint-hosted add-in.

jQuery.ajax({
        url: "http://<site url>/_api/web/lists/GetByTitle('Test')",
        type: "POST",
        data: JSON.stringify({ '__metadata': { 'type': 'SP.List' }, 'Title': 'New title' }),
        headers: { 
            "X-HTTP-Method":"MERGE",
            "accept": "application/json;odata=verbose",
            "content-type": "application/json;odata=verbose",
            "content-length": <length of post body>,
            "X-RequestDigest": $("#__REQUESTDIGEST").val(),
            "IF-MATCH": "*"
        },
        success: doSuccess,
        error: doError
});


The value of the IF-MATCH key in the request headers is where you specify the etag value of a list or list item. This particular value applies only to lists and list items, and is intended to help you avoid concurrency problems when you update those entities. The previous example uses an asterisk (*) for this value, and you can use that value whenever you don't have any reason to worry about concurrency issues. Otherwise, you should obtain the etag value or a list or list item by performing a GET request that retrieves the entity. The response headers of the resulting HTTP response pass the etag as the value of the ETag key. This value is also included in the entity metadata.The value of the IF-MATCH key in the request headers is where you specify the etag value of a list or list item. This particular value applies only to lists and list items, and is intended to help you avoid concurrency problems when you update those entities. The previous example uses an asterisk (*) for this value, and you can use that value whenever you don't have any reason to worry about concurrency issues. Otherwise, you should obtain the etag value or a list or list item by performing a GET request that retrieves the entity. The response headers of the resulting HTTP response pass the etag as the value of the ETag key. This value is also included in the entity metadata.

The following example shows the opening <entry> tag for the XML node that contains the list information. The m:etag property contains the etag value.The following example shows the opening <entry> tag for the XML node that contains the list information. The m:etag property contains the etag value.

<entry xml:base="http://site url/_api/" xmlns=http://www.w3.org/2005/Atom 
xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices" 
xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata"
xmlns:georss="http://www.georss.org/georss" xmlns:gml="http://www.opengis.net/gml" m:etag=""1"">

Crear un sitio con RESTCreating a site with REST

En el siguiente ejemplo, se muestra cómo crear un sitio en JavaScript.The following example shows how to create a site in JavaScript.

jQuery.ajax({
    url: "http://<site url>/_api/web/webinfos/add",
    type: "POST",
    data: JSON.stringify(
        {'parameters': {
            '__metadata':  {'type': 'SP.WebInfoCreationInformation' },
            'Url': 'RestSubWeb',
            'Title': 'RestSubWeb',
            'Description': 'REST created web',
            'Language':1033,
            'WebTemplate':'sts',
            'UseUniquePermissions':false}
        }
    ),
    headers: { 
        "accept": "application/json; odata=verbose", 
        "content-type":"application/json;odata=verbose",
        "content-length": <length of post body>,
        "X-RequestDigest": $("#__REQUESTDIGEST").val() 
    },
    success: doSuccess,
    error: doError
});

Nota

Setting WebTemplate to 'sts' will create a modern homepage. To create a classic homepage, set WebTemplate to 'sts#0'. Setting WebTemplate to 'sts' will create a modern homepage. To create a classic homepage, set WebTemplate to 'sts#0'.

Cómo difieren las solicitudes REST por entornoHow REST requests differ by environment

La creación y el envío de una solicitud HTTP puede variar en función del tipo de lenguaje, de biblioteca y de complemento, por lo que con frecuencia se debe cambiar uno o más componentes de la solicitud cuando se traduce una solicitud de un entorno a otro. Por ejemplo, las solicitudes de jQuery AJAX usan parámetros data y type para especificar el tipo y el cuerpo de la solicitud, pero las solicitudes de biblioteca entre dominios usan parámetros body y method para especificar dichos valores.Building and sending an HTTP request may vary according to language, library, and add-in type, so you often need to change one or more request components when you're translating a request from one environment to another. For example, jQuery AJAX requests use data and type parameters to specify the request body and type, but cross-domain library requests use body and method parameters to specify those values.

En las secciones siguientes, se describen otras diferencias comunes entre entornos.The following sections describe other common differences across environments.

La manera de obtener y enviar el valor implícito del formulario depende del complementoThe way you get and send the form digest value depends on the add-in

Al enviar una solicitud POST, hay que incluir el valor de síntesis de formulario en el encabezado X-RequestDigest. Sin embargo, la forma de obtener y enviar el valor difiere según el complemento:When you send a POST request, the request must include the form digest value in the X-RequestDigest header. However, the way you get and send the value differs by add-in:

  • En complementos hospedados en SharePoint, solo es necesario pasar el encabezado siguiente:In SharePoint-hosted add-ins, you can just pass the following header:

    "X-RequestDigest": $("#__REQUESTDIGEST").val()

  • En los complementos hospedados en la nube que usen OAuth, primero recupere el valor de síntesis de formulario enviando una solicitud al extremo de contextinfo y luego agréguelo a las solicitudes, tal como se muestra en Escritura de datos mediante la interfaz de REST.In cloud-hosted add-ins that use OAuth, first retrieve the form digest value by sending a request to the contextinfo endpoint, and then add it to requests, as shown in Writing data by using the REST interface.

  • En los complementos hospedados en la nube que usan la biblioteca entre dominios de JavaScript, no es necesario especificar el valor de síntesis de formulario. De manera predeterminada, SP.RequestExecutor lo hace automáticamente. (También controla el valor content-length).In cloud-hosted add-ins that use the JavaScript cross-domain library, you don't need to specify the form digest value. By default, SP.RequestExecutor automatically handles this for you. (It also handles the content-length value.)

Los complementos que usan OAuth deben pasar tokens de acceso en las solicitudesAdd-ins that use OAuth must pass access tokens in requests

Cloud-hosted add-ins use either OAuth or the cross-domain library to authorize access to SharePoint data. Add-in components with code that runs on a remote web server must use OAuth to authorize access to SharePoint data. In this case, you need to include an Authorization header to send the access token. For an example that adds an authorization header to an HTTPWebRequest object, see Reading data with the SharePoint REST interface.Cloud-hosted add-ins use either OAuth or the cross-domain library to authorize access to SharePoint data. Add-in components with code that runs on a remote web server must use OAuth to authorize access to SharePoint data. In this case, you need to include an Authorization header to send the access token. For an example that adds an authorization header to an HTTPWebRequest object, see Reading data with the SharePoint REST interface.

Nota

Cloud-hosted add-in components that are written in JavaScript must use the SP.RequestExecutor object in the cross-domain library to access to SharePoint data. Cross-domain library requests don't need to include an access token.Cloud-hosted add-in components that are written in JavaScript must use the SP.RequestExecutor object in the cross-domain library to access to SharePoint data. Cross-domain library requests don't need to include an access token.

Para leer más información sobre los tokens de acceso OAuth y sobre cómo obtenerlos, vea Flujo de tokens de contexto de OAuth para complementos para SharePoint y Flujo de código de autenticación de OAuth para aplicaciones en SharePoint.To learn more about OAuth access tokens and how to get them, see Context Token OAuth flow for SharePoint Add-ins and Authorization Code OAuth flow for SharePoint Add-ins.

Los URI de punto de conexión en solicitudes entre dominios usan SP.AppContextSite para cambiar el contextoEndpoint URIs in cross-domain requests use SP.AppContextSite to change the context

Las solicitudes se envían al punto de conexión del recurso que se especifica en la propiedad url de la solicitud. Los URI de punto de conexión usan el siguiente formato:Requests are sent to the resource endpoint that's specified in the url property of the request. Endpoint URIs use the following format:

<site url>/_api/<context>/<resource> (ejemplo, https://contoso.com/_api/web/lists)<site url>/_api/<context>/<resource> (example, https://contoso.com/_api/web/lists)

Las solicitudes de biblioteca entre dominios usan este formato cuando acceden a datos en la web de complemento, que es el contexto predeterminado para las solicitudes de biblioteca entre dominios. Pero para acceder a datos en la web de hospedaje o en otra colección de sitios, las solicitudes deben inicializar la web de hospedaje u otra colección de sitios como contexto. Para ello, usan el extremo SP.AppContextSite del URI, tal como se muestra en la Tabla 1. Los URI de ejemplo de la Tabla 1 usan el alias **@target** para enviar la dirección URL de destino de la cadena de consulta porque la dirección URL contiene un carácter especial (':').Cross-domain library requests use this format when they access data on the add-in web, which is the default context for cross-domain library requests. But to access data on the host web or on another site collection, the requests need to initialize the host web or other site collection as the context. To do this, they use the SP.AppContextSite endpoint in the URI, as shown in Table 1. The example URIs in Table 1 use the **@target** alias to send the target URL in the query string because the URL contains a special character (':').

Nota

Se necesita una instancia web de complemento para que un complemento hospedado en la nube pueda acceder a los datos de SharePoint cuando se use la biblioteca entre dominios.An add-in web instance is required for a cloud-hosted add-in to access SharePoint data when using the cross-domain library.

Tabla 1: Usar el punto de conexión SP.AppContextSite para cambiar el contexto de la solicitudTable 1. Using the SP.AppContextSite endpoint to change the context of the request

Tipo de complementoAdd-in type Escenario de acceso a datos entre dominiosCross-domain data access scenario URI de punto de conexión de ejemploExample endpoint URI
Hospedado en la nubeCloud-hosted Acceso de componentes de complemento de JavaScript a datos de web de host con la biblioteca entre dominiosJavaScript add-in component accessing host web data by using the cross-domain library <app web url>/_api/SP.AppContextSite(@target)/web/lists?@target='<host web url>'
Hospedado en la nubeCloud-hosted Acceso de componentes de complemento de JavaScript a datos en una colección de sitios distinta de la web de host con la biblioteca entre dominios (solo complementos con ámbito de espacio empresarial)JavaScript add-in component accessing data in a site collection other than the host web by using the cross-domain library (tenant-scoped add-ins only) <app web url>/_api/SP.AppContextSite(@target)/web/title?@target='<target site url>'
Hospedado en SharePointSharePoint-hosted Acceso de componentes web de complemento a datos en otra colección de sitios (solo complementos con ámbito de espacio empresarial)Add-in web component accessing data in another site collection (tenant-scoped add-ins only) <app web url>/_api/SP.AppContextSite(@target)/web/title?@target='<target site url>'

Nota

Los escenarios de acceso a datos entre dominios también requieren permisos de complemento adecuados. Para obtener más información, vea Acceder a datos de web de hospedaje y Acceder a datos en colecciones de sitios.Cross-domain data access scenarios also require appropriate add-in permissions. For more information, see Access data from the host web and Access data across site collections.

SharePoint Add-ins can get the add-in web URL and host web URL from the query string of the add-in page, as shown in the following code example. The example also shows how to reference the cross-domain library, which is defined in the SP.RequestExecutor.js file on the host web. The example assumes that your add-in launches from SharePoint. For guidance about setting your SharePoint context correctly when your add-in does not launch from SharePoint, see Authorization Code OAuth flow for SharePoint Add-ins.SharePoint Add-ins can get the add-in web URL and host web URL from the query string of the add-in page, as shown in the following code example. The example also shows how to reference the cross-domain library, which is defined in the SP.RequestExecutor.js file on the host web. The example assumes that your add-in launches from SharePoint. For guidance about setting your SharePoint context correctly when your add-in does not launch from SharePoint, see Authorization Code OAuth flow for SharePoint Add-ins.

var hostweburl;
var appweburl;

// Get the URLs for the add-in web the host web URL from the query string.
$(document).ready(function () {
  //Get the URI decoded URLs.
  hostweburl = decodeURIComponent(getQueryStringParameter("SPHostUrl"));
  appweburl = decodeURIComponent(getQueryStringParameter("SPAppWebUrl"));

  // Load the SP.RequestExecutor.js file.
  $.getScript(hostweburl + "/_layouts/15/SP.RequestExecutor.js", runCrossDomainRequest);
});

// Build and send the HTTP request.
function runCrossDomainRequest() {
  var executor = new SP.RequestExecutor(appweburl); 
  executor.executeAsync({
      url: appweburl + "/_api/SP.AppContextSite(@target)/web/lists?@target='" + hostweburl + "'",
      method: "GET", 
      headers: { "Accept": "application/json; odata=verbose" }, 
      success: successHandler, 
      error: errorHandler 
  });
}

// Get a query string value.
// For production add-ins, you may want to use a library to handle the query string.
function getQueryStringParameter(paramToRetrieve) {
  var params = document.URL.split("?")[1].split("&amp;");
  var strParams = "";
  for (var i = 0; i < params.length; i = i + 1) {
    var singleParam = params[i].split("=");
    if (singleParam[0] == paramToRetrieve) return singleParam[1];
  }
}
??? // success and error callback functions

Propiedades usadas en solicitudes RESTProperties used in REST requests

En la tabla 2, se muestran propiedades que se suelen usar en solicitudes HTTP para el servicio REST de SharePoint.Table 2 shows properties that are commonly used in HTTP requests for the SharePoint REST service.

Tabla 2. Cuándo usar propiedades de solicitud de REST en solicitudes HTTPTable 2. When to use REST request properties in HTTP requests

PropiedadesProperties Cuándo se requiereWhen required DescripciónDescription
urlurl Todas las solicitudesAll requests La dirección URL del extremo del recurso de REST. Ejemplo: http://<site url>/_api/web/listsThe URL of the REST resource endpoint. Example: http://<site url>/_api/web/lists
method (o type)method (or type) Todas las solicitudesAll requests El método de solicitud HTTP: GET para operaciones de lectura y POST para operaciones de escritura. Las solicitudes POST pueden realizar operaciones de actualización o eliminación especificando un verbo DELETE, MERGE o PUT en el encabezado X-HTTP-Method. The HTTP request method: GET for read operations and POST for write operations. POST requests can perform update or delete operations by specifying a DELETE, MERGE, or PUT verb in the X-HTTP-Method header.
body (o data)body (or data) Solicitudes POST que envían datos en el cuerpo de la solicitudPOST requests that send data in the request body El cuerpo de la solicitud POST. Envía datos (como tipos complejos) que no se pueden enviar en el URI de extremo. Se usa con el encabezado content-length.The body of the POST request. Sends data (such as complex types) that can't be sent in the endpoint URI. Used with the content-length header.
Encabezado AuthenticationAuthentication header Complementos remotos que usan OAuth para autenticar usuarios. No se aplica cuando se usa JavaScript o la biblioteca entre dominios.Remote add-ins that are using OAuth to authenticate users; does not apply when using JavaScript or the cross domain library Envía el token de acceso de OAuth (obtenido desde un servidor de tokens seguro del servicio de control de acceso (ACS) de Microsoft) que se usa para autenticar al usuario en la solicitud. Ejemplo: "Authorization": "Bearer " + accessToken, donde accessToken representa la variable que almacena el token. Los tokens se deben recuperar usando código del servidor. Sends the OAuth access token (obtained from a Microsoft Access Control Service (ACS) secure token server) that's used to authenticate the user for the request. Example: "Authorization": "Bearer " + accessToken, where accessToken represents the variable that stores the token. Tokens must be retrieved by using server-side code.
Encabezado X-RequestDigestX-RequestDigest header Solicitudes POST (excepto las solicitudes SP.RequestExecutor)POST requests (except SP.RequestExecutor requests) Los complementos remotos que usan OAuth deben obtener el valor de síntesis del formulario del extremo de http://<site url>/_api/contextinfo. Los complementos hospedados por SharePoint pueden obtener el valor del control de página #__REQUESTDIGEST, siempre que esté disponible en la página de SharePoint. Vea Escritura de datos mediante la interfaz de REST. Remote add-ins that use OAuth can get the form digest value from the http://<site url>/_api/contextinfo endpoint. SharePoint-hosted add-ins can get the value from the #__REQUESTDIGEST page control if it's available on the SharePoint page. See Writing data by using the REST interface.
Encabezado acceptaccept header Solicitudes que devuelven metadatos de SharePointRequests that return SharePoint metadata Especifica el formato de los datos de respuesta recibidos del servidor. El formato predeterminado es application/atom+xml. Ejemplo: "accept":"application/json;odata=verbose"Specifies the format for response data from the server. The default format is application/atom+xml. Example: "accept":"application/json;odata=verbose"
Encabezado content-typecontent-type header Solicitudes POST que envían datos en el cuerpo de la solicitudPOST requests that send data in the request body Especifica el formato de los datos que el cliente está enviando al servidor. El formato predeterminado es application/atom+xml. Ejemplo: "content-type":"application/json;odata=verbose"Specifies the format of the data that the client is sending to the server. The default format is application/atom+xml. Example: "content-type":"application/json;odata=verbose"
Encabezado content-lengthcontent-length header Solicitudes POST que envían datos en el cuerpo de la solicitud (excepto las solicitudes SP.RequestExecutor)POST requests that send data in the request body (except SP.RequestExecutor requests) Especifica la longitud del contenido. Ejemplo: "content-length":requestBody.lengthSpecifies the length of the content. Example: "content-length":requestBody.length
Encabezado IF-MATCHIF-MATCH header Solicitudes POST para las operaciones DELETE, MERGE o PUT, principalmente para cambiar listas y bibliotecas.POST requests for DELETE, MERGE, or PUT operations, primarily for changing lists and libraries Ofrece una forma de comprobar que el objeto que se está modificando no ha cambiado desde la última vez que se recuperó. También le permite especificar si quiere sobrescribir algún cambio, como se muestra en el siguiente ejemplo: "IF-MATCH":"*"Provides a way to verify that the object being changed has not been changed since it was last retrieved. Or, lets you specify to overwrite any changes, as shown in the following example: "IF-MATCH":"*"
Encabezado X-HTTP-MethodX-HTTP-Method header Solicitudes POST para las operaciones DELETE, MERGE o PUTPOST requests for DELETE, MERGE, or PUT operations Se usa para especificar que la solicitud haga una operación de actualización o eliminación. Ejemplo: "X-HTTP-Method":"PUT"Used to specify that the request performs an update or delete operation. Example: "X-HTTP-Method":"PUT"
binaryStringRequestBodybinaryStringRequestBody Solicitudes POST SP.RequestExecutor que envían datos binarios en el cuerpoSP.RequestExecutor POST requests that send binary data in the body Especifica si el cuerpo de la solicitud es una cadena binaria. Boolean.Specifies whether the request body is a binary string. Boolean.
binaryStringResponseBodybinaryStringResponseBody Solicitudes SP.RequestExecutor que devuelven datos binariosSP.RequestExecutor requests that return binary data Especifica si la respuesta es una cadena binaria o no. Boolean.Specifies whether the response is a binary string. Boolean.

Compatibilidad con trabajos por lotesBatch job support

El servicio REST de SharePoint Online (y SharePoint 2016 local o versiones posteriores) admite la combinación de varias solicitudes en una sola llamada al servicio mediante la opción de consulta $batch de OData. Para obtener más información y vínculos a los ejemplos de código, vea Realizar solicitudes de lote con las API REST.The SharePoint Online (and on-premises SharePoint 2016 and later) REST service supports combining multiple requests into a single call to the service by using the OData $batch query option. For details and links to code samples, see Make batch requests with the REST APIs.

Vea tambiénSee also