Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

UsmanBasharmal's avatar

Uploading file to onedrive using microsoft graph api

I am trying to uploading a video file to onedrive using the microsoft graph api with the php sdk implementation in laravel.

Code details as below

// Get the access token from the cache
    $tokenCache = new TokenCache();
    $accessToken = $tokenCache->getAccessToken();

    $file_name = 'new_video.mp4';
    $media_path = storage_path('video.mp4');

    // Create a Graph client
    $graph = new Graph();
    $graph->setAccessToken($accessToken);

          //create post request
    $postData = json_encode([ 'items' =>
                    [
                        "@odata.type" => "microsoft.graph.driveItemUploadableProperties",
                        "@microsoft.graph.conflictBehavior" => "rename",
                        "name" => $file_name
                    ]
                ]);
    //dd(json_encode($postData));

    try {
        $post = $graph->createRequest('POST', '/drive/root/:{item-path}:/createUploadSession')->attachBody($postData)->upload($media_path);

    } catch (\Illuminate\Http\Client\RequestException $e) {
        dd($e);
    }

Not sure what should go into the item path too, i tried using the folder name but got error and i also tried excluding the item path but still got an error.

This is the error I am getting

Client error: `POST https://graph.microsoft.com/v1.0/drive/root/createUploadSession` resulted in a `400 Bad Request` response: {
 "error": {
 "code": "BadRequest",
 "message": "Unable to read JSON request payload. Please ensure Content-T (truncated...)

Json Encode of the request data is also as below and I cant figure out the problem...

{"items":
  {
    "@odata.type":"microsoft.graph.driveItemUploadableProperties",
    "@microsoft.graph.conflictBehavior":"rename",
    "name":"new_video.mp4"
 }
}
0 likes
1 reply
yudo's avatar

I am trying to do the same thing.

{item-path} is the destination folder ID where you will put the destination file. This createUploadSession is working for me.

Your error not is related with that... it is related on the way you are passing your body object. Maybe encoding related.

I would like to see some sort of complete example of this procedure. I found simple upload examples but not Session uploads.

Did you found any good example?

Please or to participate in this conversation.