I’m working on a Laravel project where I need to call an external API from RapidAPI. I’ve been trying to use unirest library but I keep getting errors. I followed the documentation but something isn’t working right. Maybe there’s a better way to do this? Any help would be great!
Here’s what I have in my controller:
public function create(Request $request)
{
User::create(
request()->validate([
'first_name' => ['required','max:255'],
'last_name' => ['required','max:255'],
],
[
'first_name.required' => 'Please enter your first name',
'last_name.required' => 'Please enter your last name'
]));
$headers = array('Accept' => 'application/json');
$response = Unirest\Request::post("ENDPOINT_URL",
array(
"X-RapidAPI-Key" => "MY_API_KEY"
)
);
dd($response);
return view("success");
}
The error I’m getting:
Class ‘App\Http\Controllers\Unirest\Request’ not found
yeah, that unirest namespace thing is annoying. add use Unirest\Request; at the top of your controller or just use \Unirest\Request::post() instead. but honestly, guzzle’s probably better for rapidapi calls than unirest anyway.
Ditch unirest and use Laravel’s HTTP client instead. Way cleaner and works great with RapidAPI. I ran into the same problems with unirest when I first started using RapidAPI.
Replace your API call with this:
$response = Http::withHeaders([
'X-RapidAPI-Key' => 'YOUR_API_KEY',
'X-RapidAPI-Host' => 'your-api-host.rapidapi.com',
'Content-Type' => 'application/json'
])->post('ENDPOINT_URL', [
// your payload here
]);
$data = $response->json();
Add use Illuminate\Support\Facades\Http; at the top of your controller. The HTTP facade works in Laravel 7+ and handles everything for you. Way more reliable than third-party libraries.
I’ve been using RapidAPI for 2 years and cURL is still my favorite for Laravel controllers. It’s reliable and doesn’t need extra dependencies. Here’s my usual setup:
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => 'YOUR_RAPIDAPI_ENDPOINT',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => [
'X-RapidAPI-Key: YOUR_API_KEY',
'X-RapidAPI-Host: your-host.rapidapi.com',
'Content-Type: application/json'
],
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => json_encode($your_data)
]);
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
// handle error
} else {
$data = json_decode($response, true);
}
You get complete control over requests and error handling. Works with any Laravel version too - no compatibility headaches.
This topic was automatically closed 4 days after the last reply. New replies are no longer allowed.