Search code examples
javascriptsharepointmicrosoft-graph-api

How to create new sharepoint list with a lookup column using Graph API?


EDIT: typo

I'm working on a server side service that should create a new Sharepoint List Using Graph API. This list should later be used by humans, so I just have to create the structure.

As long as I try to create a simple list with just text field everything is working correctly. Now I have to add a lookup column to the list. This lookup column should refer to another list in the same site and give the user the ability to select one of the items coming from the source list.

To be precise this is the code I'm currently trying. I have tried multiple other "solutions" I've found online with no success.

const financeList = {
      displayName: `testlist`,
      columns: [
        { name: "Entity", text: {} },
        { name: "Justification", text: {} },
        { name: "Deescription", text: {} },
        {
          name: "MacroExpenseItem",
          lookup: {
            listId: "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
            columnId: "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
          },
        },
        { name: "Note", text: {} },
      ],
      list: {
        template: "genericList",
      },
    };

    const newFinanceList = await graph
      .api(newListURL)
      .version("beta")
      .post(financeList);

For privacy reasons I hid the listId and columnId, but I'm sure those ids are correct in my real code.

Running this creates the list and sets the column as Lookup, but the filed does not refer to the source list and remains blank.

Is it even possible to create such a lookup filed?

I have tried various solutions with no effect. Tried using only the listId, tried creating a base list to duplicate, and I don't remember how many other.


Solution

  • You need to use either columnName or primaryLookupColumnId instead of columnId. There is no columnId property

    const financeList = {
          displayName: `testlist`,
          columns: [
            { name: "Entity", text: {} },
            { name: "Justification", text: {} },
            { name: "Deescription", text: {} },
            {
              name: "MacroExpenseItem",
              lookup: {
                listId: "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
                columnName: "column_name",
              },
            },
            { name: "Note", text: {} },
          ],
          list: {
            template: "genericList",
          },
        };
    
        const newFinanceList = await graph
          .api(newListURL)
          .version("beta")
          .post(financeList);
    

    Resource:

    Lookup column