Contact Us

Sitecore PowerShell extensions (SPEs) are powerful tools to improve productivity by significantly reducing the amount of time it takes to deliver any Sitecore solution. 

In this blog, we will delve deeper into creating a Sitecore PowerShell script to hit an API that contains data in the JSON form and subsequently create items in the backend. 

JSON data is a fairly common data type that we may encounter very frequently, especially while hitting APIs. These may include data from external databases such as Twitter but more often they contain internal data that is specific to your organization. 

It is often extremely beneficial to be able to use and leverage data from different sources but at the same time can feel difficult due to the complex nature of JSON data.

The following chronological steps will elucidate how to go about hitting APIs and creating items in Sitecore’s backend while managing and parsing data in the JSON format:

 
  1. Firstly, begin with creating Mock WebAPI 

    Url - https://Myapi.local/api/Employee ?noofRecords=100&idStarts=1

    Jsondata

  2. Create a template in Sitecore feature inside(Employeetemplate)

     

    In the below screenshot;

    template

    • Go to Sitecore PowerShell ISE
    • Open ‘Write the code’ Or paste the code into the editor.
    • You may find the necessary script below to incorporate it similarly as demonstrated in the screenshot below.

      script

    $GetAPI_EMPDetails = @{“URI” = ‘https://Myapi.local/api/Employee ?noofRecords=100&idStarts=1’}
    $data = Invoke-RestMethod @GetAPI_EMPDetails
    $itemPath ="/sitecore/content/MyTraining/Demo/Home/EmployeeData"
    $templateID="{1403A7D9-FA72-490B-B0E1-E9FD991731DD}"
     
    foreach($i in $data)
    {
        
        write-host($i.firstName + ' Name ')
        $item = New-Item -Path $itemPath -Name $i.FirstName  -ItemType $templateID
     
        $item.Editing.BeginEdit()
        
        $item["FirstName"]= $i.firstName
        
        $item["LastName"]= $i.lastName
        
        $item["DOB"]= $i.dob
        
        $item["Address"]= $i.address
        
        $item["ContactNumber"]=$i.contactNumber
        
        $item["Salary"]= $i.salary
        
        $item.Editing.EndEdit()
    }

    1. Go ahead and Execute.
    2. Finally, go to Home Node and check the Employee Pagefolder as shown below in the screenshot.

      newteplate

     

Conclusion 

Following the aforementioned steps will help relieve certain complexities associated with parsing JSON data while hitting APIs. As demonstrated, this process becomes a lot easier when we turn such data into Sitecore PowerShell objects.

Do you still have questions or are keen to learn more? Do not hesitate and reach out to us for immediate, efficient, and personalized consultation and execution guided by our certified experts.

Need Help?