How to add a file to SPO using REST API?

Here is the PowerShell code for it.

## Replace bold letter with your environments.

$url = 'https://accounts.accesscontrol.windows.net/YOUR-TENANT-ID/tokens/OAuth/2'

$headers = @{
    'Content-Type' = 'application/x-www-form-urlencoded'
     'Accept' = '*/*'
}

$client_Id = 'YOUR-CLIENT-ID'
$client_secrect = 'YOUR-CLIENT-SECRET'
$TenantID = 'YOUR-TENANT-ID'
$TenantName ='YOUR-TENANT-NAME'

$body = $("grant_type=client_credentials&client_id={0}%40{1}&client_secret={2}%3D&resource=00000003-0000-0ff1-ce00-000000000000%2F{3}.sharepoint.com%40{4}" -f $client_Id,$TenantID,$client_secrect,$TenantName,$TenantID)

$item = Invoke-WebRequest -Method POST -Uri $url -Headers $headers -Body $body -UseBasicParsing

$response = ConvertFrom-Json $item

$url='https://YOUR-TENANT-NAME.sharepoint.com/sites/test123/_api/web/GetFolderByServerRelativePath(decodedurl=%27Shared Documents%27)/Files/add(url=%27NAME-OF_FILE.csv%27,overwrite=true)'

$headers = @{
'Authorization' = $("{0} {1}" -f $response.token_type,$response.access_token)
'Accept' = 'application/json; odata=verbose'
'Content-Type' = 'text/csv'
}
$r = Get-Content C:\0-VA\NAME-OF_FILE.csv | `
Invoke-WebRequest -Method POST -Uri $url -Headers $headers -UseBasicParsing

Note: To get client id and secret use the following link.

http://www.ktskumar.com/2017/01/access-sharepoint-online-using-postman/

About Pankaj

I am a Developer and my linked profile is https://www.linkedin.com/in/pankajsurti/
This entry was posted in SharePoint, SharePoint 2010, SharePoint 2013. Bookmark the permalink.

1 Response to How to add a file to SPO using REST API?

  1. Pingback: Azure Security Group Automation [Guest Post] | The SQL Pro

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s