SharePoint exposes a REST interface that allows us to perform basic create, read, update, and delete (CRUD) operations on its entities. These operations are performed by constructing a RESTful HTTP request, using the OData standard, that 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. This means, to perform any operation using 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.

Endpoints that represents read operations are access using HTTP GET request. Endpoints that represents create operations map to HTTP POST. When you’re updating entities, you use PUT or MERGE HTTP request. Use the DELETE method to delete the entity.

I mentioned we can use PUT or MERGE request when updating entities, so which one is preferable? The answer is none, it depends on what you want to achieve. 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.

Request Authentication

All request to SharePoint endpoints will be authenticated. The method you will use to authenticate will vary based on how you are accessing the endpoints.

You need to get an access token when you use OAuth authentication. 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. 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.

Reading data with the SharePoint REST interface

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. You also need a valid OAuth access token.

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.

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.

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

Writing data by using the REST interface

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. 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. 

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
});

In Provider-hosted add-ins that use OAuth, first retrieve the form digest 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.

Another option is using the JavaScript cross-domain library. For provider hosted page, the HTTP requests will be from a remote webpage. For security, browsers do not allow JavaScript that is hosted on one domain to access resources on another domain. The JavaScript cross-domain library SP.RequestExecutor handles getting and sending the form digest value for you. (It also handles the content-length value.)

var executor = new SP.RequestExecutor(appweburl);
executor.executeAsync(
    {
        url:"http://<site url>/_api/web/lists",
        method: "GET",
        success: successHandler,
        error: errorHandler
    }
);

Properties used in REST requests

The table shows properties that are commonly used in HTTP requests for the SharePoint REST service.

Properties When required Description
url All requests The URL of the REST resource endpoint. Example: http://<site url>/_api/web/lists
method (or type) All requests The HTTP request method: GET for read operations and POST for write operations. POST requests can perform update or delete operations by specifying a DELETEMERGE, or PUT verb in the X-HTTP-Method header.
body (or data) POST requests that send data in the request body 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.
Authentication header Remote add-ins that are using OAuth to authenticate users; does not apply when using JavaScript or the cross domain library 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.
X-RequestDigest header POST requests (except SP.RequestExecutor requests) 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.
accept header Requests that return SharePoint metadata Specifies the format for response data from the server. The default format is application/atom+xml. Example: “accept”:”application/json;odata=verbose”
content-type header POST requests that send data in the request body 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”
content-length header POST requests that send data in the request body (except SP.RequestExecutor requests) Specifies the length of the content. Example: “content-length”:requestBody.length
IF-MATCH header POST requests for DELETEMERGE, or PUT operations, primarily for changing lists and libraries 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”:”*”
X-HTTP-Method header POST requests for DELETEMERGE, or PUT operations Used to specify that the request performs an update or delete operation. Example: “X-HTTP-Method”:”PUT”
binaryStringRequestBody SP.RequestExecutor POST requests that send binary data in the body Specifies whether the request body is a binary string. Boolean.
binaryStringResponseBody SP.RequestExecutor requests that return binary data Specifies whether the response is a binary string. Boolean.

References

https://docs.microsoft.com/en-us/sharepoint/dev/sp-add-ins/sharepoint-net-server-csom-jsom-and-rest-api-index

https://docs.microsoft.com/en-us/previous-versions/office/developer/sharepoint-rest-reference/jj860569(v=office.15)