How to send saved file to external api in laravel?

Member

by mac , in category: PHP Frameworks , 3 months ago

How to send saved file to external api in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by tressie.damore , a day ago

@mac 

To send a saved file to an external API in Laravel, you can use the Guzzle HTTP client to make a POST request with the file as a part of the request payload. Here's an example of how you can achieve this:

  1. First, install Guzzle HTTP client by running the following command in your terminal:
1
composer require guzzlehttp/guzzle


  1. In your controller or service where you have the saved file, you can use the following code to send the file to the external API:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
use GuzzleHttpClient;

public function sendFileToExternalApi()
{
    $client = new Client();

    $file_path = storage_path('app/file_to_send.txt');
    $file = file_get_contents($file_path);

    $response = $client->request('POST', 'http://example.com/api/endpoint', [
        'multipart' => [
            [
                'name'     => 'file',
                'contents' => $file,
                'filename' => 'file_to_send.txt'
            ]
        ]
    ]);

    $response_body = $response->getBody()->getContents();

    return $response_body;
}


In the code above, we first create a new instance of the Guzzle HTTP client. We then read the contents of the saved file and create a multipart request payload with the file as part of it. Finally, we make a POST request to the external API endpoint and get the response body.


Make sure to replace the http://example.com/api/endpoint with the actual URL of the external API endpoint where you want to send the file.


That's it! You have successfully sent the saved file to an external API in Laravel using Guzzle HTTP client.