How To Upload a File Attachment Using Service Now API

This tutorial help to upload attachment into service-now using API. I am using service now attachment API to upload file into the existing SCR request.

I am taking laravel API sample to demonstrate upload functionality, You can convert this PHP source code into any other language, You can take reference from here and implement it into your preferred language.

The Attachment API allows you to upload and query file attachments. You can upload or retrieve a single file with each request.

Add a file Attachment in Using Service Now API

Let’s create a file TestController.php into Http/Controller/ folder, which ll have all code to upload a file.

Step 1: Created an API endpoint into the routes/api.php file.

$api->post('/add_attachment/{scr}', 'App\Http\Controllers\[email protected]');

Step 2: Created a client into the service file, I have created a client method into the testController.php file.

private function _client($content_type) { $base64 = base64_encode(getenv('USER').":".getenv('PASS')); $endpoint = getenv('API_URL'); $client = new Client([ 'base_uri' => $endpoint, 'timeout' => 300.0, 'headers' => ['Content-Type' => $content_type, 'Authorization' => "Basic " . $base64], 'http_errors' => false, 'verify' => false ]); return $client; }

Step 3: Created a method that will use to upload a file into service now.

public function uploadScrFile($scrNum, $file) { $content_type = $file->getMimeType(); $file_name = $file->getClientOriginalName(); return array('content_type' => $content_type, 'file_name' => $file_name); //echo '<pre/>';print_r($file_name);die; $scrRes = $this->findScrByName($scrNum); $sysid = head($scrRes['results'])['sys_id']['value']; $client = $this->_client($content_type); \Log::info("Attach File in SCR"); try { \Log::info("SCR number:", array("SCR" => $scrNum)); $response = $client->post("attachment/file?table_name=test&table_sys_id=$sysid&file_name=$file_name", ['body' => fopen($file->getRealPath(), "r")]); $response = json_decode($response->getBody(), true); return ['results' => $response['result']]; } catch (\Exception $ex) { throw new BadRequestException('bad_req', $ex->getMessage()); } }

Step 4: Finally, Create a controller method that will call the service method to upload a file.

public function uploadScrFile(Request $request, $scr) { $file = $request->files->get('file'); return $this->response->array((array) $this->uploadScrFile($scr, $file)); }

Originally published at on October 17, 2022.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Parvez Alam

Hey, I am Parvez Alam. A software developer since 2009. I love learning and sharing knowledge.