Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to seperate base URL and endpoint in laravel http client api call?

Like in guzzle, I want to seperate base URL and end point

use Guzzle\Http\Client;
use Guzzle\Stream\PhpStreamRequestFactory;

$client = new Client('https://stream.twitter.com/');//base url

$request = $client->post('statuses/2',123);//end point


like image 429
Akshay Gireesh Avatar asked Oct 21 '25 15:10

Akshay Gireesh


2 Answers

Yes, it's possible. It has a method called baseUrl().

Laravel provides an expressive, minimal API around the Guzzle HTTP client, allowing you to quickly make outgoing HTTP requests to communicate with other web applications.

 $response = Http::baseUrl("https://reqres.in/api")->get('users');

Another way is to create macros .Define the macro within the boot method of your application's App\Providers\AppServiceProvider class:

<?php

namespace App\Providers;

use Illuminate\Support\Facades\Http;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        
        Http::macro('reqres', function () {
            return Http::baseUrl('https://reqres.in/api');
        });
    }
}

and now you can reuse this method like below.

 $response  = Http::reqres()->get('users');

For post method

 $response  = Http::reqres()->post('users',[
        "name"=> "morpheus",
        "job"=> "leader"
    ]);

There are lots of built-in methods, which you can refer to here HTTP Client

Dont forget to import facades

use Illuminate\Support\Facades\Http;

If you want to use Guzzle then

$client = new GuzzleHttp\Client(['base_uri' => 'https://reqres.in/api/']);

$response = $client->request('GET', 'users');
like image 125
John Lobo Avatar answered Oct 23 '25 05:10

John Lobo


Maybe you want something like this?

$client = Http::baseUrl("https://stream.twitter.com/");
$response2 = $client->post('statuses/2',["status"=>"success"]);
$response3 = $client->post('statuses/3',["status"=>"success"]);
like image 39
nay Avatar answered Oct 23 '25 03:10

nay



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!