Skip to content
This repository was archived by the owner on Aug 28, 2024. It is now read-only.

Basic Operations

Patrick Rodgers edited this page Jan 4, 2017 · 4 revisions

This article describes completing basic operations using the JS core library. It assumes you have added the library to your project either via CDN, bower, or npm package.

Quick note on notation

All of the samples posted below are TypeScript examples. If you are using the library directly in JavaScript they will all still work, with a few modifications.

  • Where you see something like pnp.sp.* just replace it with $pnp.sp.*
  • Where you see something like:
    import { Web } from "sp-pnp-js";
    let w = new Web("{Site Url"});
    
    use:
    var w = new $pnp.Web("{Site Url}");
    

Read Data

The simplest thing you can do is read data. Below are several examples of reading data. As you can see the get method returns a Promise. For GET operations you must call the get() method to finalize the property chain and execute the request. It is also good practice to include a catch() in your promise handling chain to ensure you track and handle any errors.

import pnp from "sp-pnp-js";

// GET /_api/web
pnp.sp.web.get().then(r => {
    
    console.log(r);
});

// GET /_api/web/lists
pnp.sp.web.lists.get().then(r => {
    
    console.log(r);
});

// GET /_api/web/lists/getByTitle('Tasks')
pnp.sp.web.lists.getByTitle("Tasks").get().then(r => {
    
    console.log(r);
});

// GET /_api/web/lists/getByTitle('Tasks')/items
pnp.sp.web.lists.getByTitle("Tasks").items.get().then(r => {
    
    console.log(r);
});

// GET /_api/web/lists/getByTitle('Tasks')/items(1)
pnp.sp.web.lists.getByTitle("Tasks").items.getById(1).get().then(r => {
    
    console.log(r);
});

OData Operators

The library also supports the OData operations select and expand for instances (such as a list or an item) as well we the select, filter, expand, orderBy, skip, and top operations for collections (collection of lists, or items). Some examples are provided below:

import pnp from "sp-pnp-js";

pnp.sp.web.select("Title", "AllProperties").expand("AllProperties").get().then(r => {
    
    console.log(r);
});

pnp.sp.web.lists.getByTitle("Tasks").items.filter("Title eq 'Value'").top(2).orderBy("Modified").get().then(r => {
    
    console.log(r);
});

// Getting the second "page" of results from the top query
pnp.sp.web.lists.getByTitle("Tasks").items.filter("Title eq 'Value'").skip(2).top(2).orderBy("Modified").get().then(r => {
    
    console.log(r);
});

Clone this wiki locally