Welcome to the SharpAPI Laravel Integration Guide! This repository provides a comprehensive, step-by-step tutorial on how to integrate SharpAPI into your next Laravel AI application. Whether you're looking to enhance your app with** AI-powered features** or automate workflows, this guide will walk you through the entire process, from authentication to making API calls and handling responses.
Article published also as a Github repository at https://github.com/sharpapi/laravel-ai-integration-guide.
Table of Contents
- Prerequisites
- Setting Up the Laravel Project
- Installing the SharpAPI PHP Client
-
Configuration
- Environment Variables
- Authentication with SharpAPI
-
Making API Calls
- Example: Generating a Job Description
- Handling Responses
- Error Handling
- Testing the Integration
-
Advanced Usage
- Asynchronous Requests
- Caching Responses
- Conclusion
- Support
- License
Prerequisites
Before you begin, ensure you have met the following requirements:
- PHP: >= 8.1
- Composer: Dependency manager for PHP
- Laravel: Version 9 or higher
- SharpAPI Account: Obtain an API key from SharpAPI.com
- Basic Knowledge of Laravel: Familiarity with Laravel framework and MVC architecture
Setting Up the Laravel Project
If you already have a Laravel project, you can skip this step. Otherwise, follow these instructions to create a new Laravel project.
- Install Laravel via Composer
composer create-project --prefer-dist laravel/laravel laravel-ai-integration-guide
- Navigate to the Project Directory
cd laravel-ai-integration-guide
- Serve the Application
php artisan serve
The application will be accessible at http://localhost:8000.
Installing the SharpAPI PHP Client
To interact with SharpAPI, you'll need to install the SharpAPI PHP client library.
Require the SharpAPI Package via Composer
composer require sharpapi/sharpapi-laravel-client php artisan vendor:publish --tag=sharpapi-laravel-client
Configuration
Environment Variables
Storing sensitive information like API keys in environment variables is a best practice. Laravel uses the .env file for environment-specific configurations.
- Open the .env File
Located in the root directory of your Laravel project.
- Add Your SharpAPI API Key
SHARP_API_KEY=your_actual_sharpapi_api_key_here
Note: Replace your_actual_sharpapi_api_key_here with your actual SharpAPI API key.
- Accessing Environment Variables in Code
Laravel provides the env helper function to access environment variables.
$apiKey = env('SHARP_API_KEY');
Authentication with SharpAPI
Authentication is required to interact with SharpAPI's endpoints securely.
- Initialize the SharpAPI Client
Create a service or use it directly in your controllers.
<?php namespace App\Services; use SharpAPI\SharpApiService; class SharpApiClient { protected $client; public function __construct() { $this->client = new SharpApiService(env('SHARP_API_KEY')); } public function getClient() { return $this->client; } }
- Binding the Service in a Service Provider (Optional)
This allows you to inject the service wherever needed.
<?php namespace App\Providers; use Illuminate\Support\ServiceProvider; use App\Services\SharpApiClient; class AppServiceProvider extends ServiceProvider { public function register() { $this->app->singleton(SharpApiClient::class, function ($app) { return new SharpApiClient(); }); } public function boot() { // } }
- Using the Service in a Controller
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Services\SharpApiClient; class SharpApiController extends Controller { protected $sharpApi; public function __construct(SharpApiClient $sharpApi) { $this->sharpApi = $sharpApi->getClient(); } public function ping() { $response = $this->sharpApi->ping(); return response()->json($response); } }
- Defining Routes
Add routes to routes/web.php or routes/api.php:
use App\Http\Controllers\SharpApiController; Route::get('/sharpapi/ping', [SharpApiController::class, 'ping']);
Making API Calls
Once authenticated, you can start making API calls to various SharpAPI endpoints. Below are examples of how to interact with different endpoints.
Example: Generating a Job Description
- Create a Job Description Parameters DTO
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Services\SharpApiClient; use SharpAPI\Dto\JobDescriptionParameters; class SharpApiController extends Controller { protected $sharpApi; public function __construct(SharpApiClient $sharpApi) { $this->sharpApi = $sharpApi->getClient(); } public function generateJobDescription() { $jobDescriptionParams = new JobDescriptionParameters( "Software Engineer", "Tech Corp", "5 years", "Bachelor's Degree in Computer Science", "Full-time", [ "Develop software applications", "Collaborate with cross-functional teams", "Participate in agile development processes" ], [ "Proficiency in PHP and Laravel", "Experience with RESTful APIs", "Strong problem-solving skills" ], "USA", true, // isRemote true, // hasBenefits "Enthusiastic", "Category C driving license", "English" ); $statusUrl = $this->sharpApi->generateJobDescription($jobDescriptionParams); $resultJob = $this->sharpApi->fetchResults($statusUrl); return response()->json($resultJob->getResultJson()); } }
- Define the Route
Route::get('/sharpapi/generate-job-description', [SharpApiController::class, 'generateJobDescription']);
- Accessing the Endpoint
Visit http://localhost:8000/sharpapi/generate-job-description to see the generated job description.
Handling Responses
SharpAPI responses are typically encapsulated in job objects. To handle these responses effectively:
- Understanding the Response Structure
{ "id": "uuid", "type": "JobType", "status": "Completed", "result": { // Result data } }
- Accessing the Result
Use the provided methods to access the result data.
$resultJob = $this->sharpApi->fetchResults($statusUrl); $resultData = $resultJob->getResultObject(); // As a PHP object // or $resultJson = $resultJob->getResultJson(); // As a JSON string
- Example Usage in Controller
public function generateJobDescription() { // ... (initialize and make API call) if ($resultJob->getStatus() === 'Completed') { $resultData = $resultJob->getResultObject(); // Process the result data as needed return response()->json($resultData); } else { return response()->json(['message' => 'Job not completed yet.'], 202); } }
Error Handling
Proper error handling ensures that your application can gracefully handle issues that arise during API interactions.
- Catching Exceptions
Wrap your API calls in try-catch blocks to handle exceptions.
public function generateJobDescription() { try { // ... (initialize and make API call) $resultJob = $this->sharpApi->fetchResults($statusUrl); return response()->json($resultJob->getResultJson()); } catch (\Exception $e) { return response()->json([ 'error' => 'An error occurred while generating the job description.', 'message' => $e->getMessage() ], 500); } }
- Handling API Errors
Check the status of the job and handle different statuses accordingly.
if ($resultJob->getStatus() === 'Completed') { // Handle success } elseif ($resultJob->getStatus() === 'Failed') { // Handle failure $error = $resultJob->getResultObject()->error; return response()->json(['error' => $error], 400); } else { // Handle other statuses (e.g., Pending, In Progress) return response()->json(['message' => 'Job is still in progress.'], 202); }
Testing the Integration
Testing is crucial to ensure that your integration with SharpAPI works as expected.
- Writing Unit Tests
Use Laravel's built-in testing tools to write unit tests for your SharpAPI integration.
<?php namespace Tests\Feature; use Tests\TestCase; use App\Services\SharpApiClient; use SharpAPI\Dto\JobDescriptionParameters; class SharpApiTest extends TestCase { protected $sharpApi; protected function setUp(): void { parent::setUp(); $this->sharpApi = new SharpApiClient(); } public function testPing() { $response = $this->sharpApi->ping(); $this->assertEquals('OK', $response['status']); } public function testGenerateJobDescription() { $jobDescriptionParams = new JobDescriptionParameters( "Backend Developer", "InnovateTech", "3 years", "Bachelor's Degree in Computer Science", "Full-time", ["Develop APIs", "Optimize database queries"], ["Proficiency in PHP and Laravel", "Experience with RESTful APIs"], "USA", true, true, "Professional", "Category B driving license", "English" ); $statusUrl = $this->sharpApi->generateJobDescription($jobDescriptionParams); $resultJob = $this->sharpApi->fetchResults($statusUrl); $this->assertEquals('Completed', $resultJob->getStatus()); $this->assertNotEmpty($resultJob->getResultObject()); } // Add more tests for other methods... }
- Running Tests
Execute your tests using PHPUnit.
./vendor/bin/phpunit
Advanced Usage
Asynchronous Requests
For handling multiple API requests concurrently, consider implementing asynchronous processing using Laravel Queues.
- Setting Up Queues
Configure your queue driver in the .env file.
QUEUE_CONNECTION=database
Run the necessary migrations.
php artisan queue:table php artisan migrate
- Creating a Job
php artisan make:job ProcessSharpApiRequest
<?php namespace App\Jobs; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; use App\Services\SharpApiClient; use SharpAPI\Dto\JobDescriptionParameters; class ProcessSharpApiRequest implements ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; protected $params; public function __construct(JobDescriptionParameters $params) { $this->params = $params; } public function handle(SharpApiClient $sharpApi) { $statusUrl = $sharpApi->generateJobDescription($this->params); $resultJob = $sharpApi->fetchResults($statusUrl); // Handle the result... } }
- Dispatching the Job
use App\Jobs\ProcessSharpApiRequest; public function generateJobDescriptionAsync() { $jobDescriptionParams = new JobDescriptionParameters( // ... parameters ); ProcessSharpApiRequest::dispatch($jobDescriptionParams); return response()->json(['message' => 'Job dispatched successfully.']); }
- Running the Queue Worker
php artisan queue:work
Caching Responses
To optimize performance and reduce redundant API calls, implement caching.
- Using Laravel's Cache Facade
use Illuminate\Support\Facades\Cache; public function generateJobDescription() { $cacheKey = 'job_description_' . md5(json_encode($jobDescriptionParams)); $result = Cache::remember($cacheKey, 3600, function () use ($jobDescriptionParams) { $statusUrl = $this->sharpApi->generateJobDescription($jobDescriptionParams); $resultJob = $this->sharpApi->fetchResults($statusUrl); return $resultJob->getResultJson(); }); return response()->json(json_decode($result, true)); }
- Invalidating Cache
When the underlying data changes, ensure to invalidate the relevant cache.
Cache::forget('job_description_' . md5(json_encode($jobDescriptionParams)));
Conclusion
Integrating SharpAPI into your Laravel application unlocks a myriad of AI-powered functionalities, enhancing your application's capabilities and providing seamless workflow automation. This guide has walked you through the essential steps, from setting up authentication to making API calls and handling responses. With the examples and best practices provided, you're well-equipped to leverage SharpAPI's powerful features in your Laravel projects.
Support
If you encounter any issues or have questions regarding the integration process, feel free to open an issue on the GitHub repository or contact our support team at contact@sharpapi.com.
License
This project is licensed under the MIT License.
The above is the detailed content of SharpAPI Laravel Integration Guide. For more information, please follow other related articles on the PHP Chinese website!

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

PHP logging is essential for monitoring and debugging web applications, as well as capturing critical events, errors, and runtime behavior. It provides valuable insights into system performance, helps identify issues, and supports faster troubleshoot

Laravel simplifies HTTP verb handling in incoming requests, streamlining diverse operation management within your applications. The method() and isMethod() methods efficiently identify and validate request types. This feature is crucial for building

The Storage::download method of the Laravel framework provides a concise API for safely handling file downloads while managing abstractions of file storage. Here is an example of using Storage::download() in the example controller:


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Chinese version
Chinese version, very easy to use

Dreamweaver Mac version
Visual web development tools

WebStorm Mac version
Useful JavaScript development tools

Notepad++7.3.1
Easy-to-use and free code editor

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.
