Maison  >  Article  >  développement back-end  >  Guide d'intégration SharpAPI Laravel

Guide d'intégration SharpAPI Laravel

Mary-Kate Olsen
Mary-Kate Olsenoriginal
2024-10-07 06:07:29690parcourir

SharpAPI Laravel Integration Guide

Bienvenue dans le Guide d'intégration SharpAPI Laravel ! Ce référentiel fournit un didacticiel complet, étape par étape, sur la façon d'intégrer SharpAPI dans votre prochaine application Laravel AI. Que vous cherchiez à améliorer votre application avec** des fonctionnalités basées sur l'IA** ou à automatiser les flux de travail, ce guide vous guidera tout au long du processus, de l'authentification à l'exécution d'appels API et à la gestion des réponses.

Article publié également sous forme de référentiel Github sur https://github.com/sharpapi/laravel-ai-integration-guide.


Table des matières

  1. Prérequis
  2. Configuration du projet Laravel
  3. Installation du client PHP SharpAPI
  4. Configuration
    • Variables d'environnement
  5. Authentification avec SharpAPI
  6. Effectuer des appels API
    • Exemple : Générer une description de poste
  7. Gestion des réponses
  8. Gestion des erreurs
  9. Test de l'intégration
  10. Utilisation avancée
    • Demandes asynchrones
    • Mise en cache des réponses
  11. Conclusion
  12. Assistance
  13. Licence

Conditions préalables

Avant de commencer, assurez-vous de remplir les conditions suivantes :

  • PHP : >= 8.1
  • Composer : Gestionnaire de dépendances pour PHP
  • Laravel : Version 9 ou supérieure
  • Compte SharpAPI : Obtenez une clé API sur SharpAPI.com
  • Connaissance de base de Laravel : Familiarité avec le framework Laravel et l'architecture MVC

Mise en place du projet Laravel

Si vous avez déjà un projet Laravel, vous pouvez ignorer cette étape. Sinon, suivez ces instructions pour créer un nouveau projet Laravel.

  1. Installer Laravel via Composer

   composer create-project --prefer-dist laravel/laravel laravel-ai-integration-guide


  1. Accédez au répertoire du projet

   cd laravel-ai-integration-guide


  1. Servir l'application

   php artisan serve


L'application sera accessible sur http://localhost:8000.


Installation du client PHP SharpAPI

Pour interagir avec SharpAPI, vous devrez installer la bibliothèque client PHP SharpAPI.

Exiger le package SharpAPI via Composer


composer require sharpapi/sharpapi-laravel-client
php artisan vendor:publish --tag=sharpapi-laravel-client



Configuration

Variables d'environnement

Le stockage d'informations sensibles telles que les clés API dans des variables d'environnement est une bonne pratique. Laravel utilise le fichier .env pour les configurations spécifiques à l'environnement.

  1. Ouvrez le fichier .env

Situé dans le répertoire racine de votre projet Laravel.

  1. Ajoutez votre clé API SharpAPI

   SHARP_API_KEY=your_actual_sharpapi_api_key_here


Remarque : Remplacez your_actual_sharpapi_api_key_here par votre clé API SharpAPI actuelle.

  1. Accès aux variables d'environnement dans le code

Laravel fournit la fonction d'assistance env pour accéder aux variables d'environnement.


   $apiKey = env('SHARP_API_KEY');



Authentification avec SharpAPI

Une authentification est requise pour interagir en toute sécurité avec les points de terminaison de SharpAPI.

  1. Initialiser le client SharpAPI

Créez un service ou utilisez-le directement dans vos contrôleurs.


   <?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;
       }
   }


  1. Liaison du service chez un fournisseur de services (facultatif)

Cela vous permet d'injecter le service partout où c'est nécessaire.


   <?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()
       {
           //
       }
   }


  1. Utilisation du service dans un contrôleur

   <?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);
       }
   }


  1. Définir des itinéraires

Ajouter des routes à routes/web.php ou routes/api.php :


   use App\Http\Controllers\SharpApiController;

   Route::get('/sharpapi/ping', [SharpApiController::class, 'ping']);



Effectuer des appels API

Une fois authentifié, vous pouvez commencer à effectuer des appels API vers différents points de terminaison SharpAPI. Vous trouverez ci-dessous des exemples d'interaction avec différents points de terminaison.

Exemple : générer une description de poste

  1. Créer une description de poste Paramètres 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());
       }
   }


  1. Définir l'itinéraire

   Route::get('/sharpapi/generate-job-description', [SharpApiController::class, 'generateJobDescription']);


  1. Accès au point de terminaison

Visitez http://localhost:8000/sharpapi/generate-job-description pour voir la description de poste générée.


Gestion des réponses

Les réponses SharpAPI sont généralement encapsulées dans des objets de travail. Pour gérer ces réponses efficacement :

  1. Comprendre la structure de réponse

   {
       "id": "uuid",
       "type": "JobType",
       "status": "Completed",
       "result": {
           // Result data
       }
   }


  1. Accès au résultat

Utilisez les méthodes fournies pour accéder aux données de résultat.


   $resultJob = $this->sharpApi->fetchResults($statusUrl);
   $resultData = $resultJob->getResultObject(); // As a PHP object
   // or
   $resultJson = $resultJob->getResultJson(); // As a JSON string


  1. 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.

  1. 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);
       }
   }


  1. 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.

  1. 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...
   }


  1. 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.

  1. 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


  1. 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...
       }
   }


  1. Dispatching the Job

   use App\Jobs\ProcessSharpApiRequest;

   public function generateJobDescriptionAsync()
   {
       $jobDescriptionParams = new JobDescriptionParameters(
           // ... parameters
       );

       ProcessSharpApiRequest::dispatch($jobDescriptionParams);
       return response()->json(['message' => 'Job dispatched successfully.']);
   }


  1. Running the Queue Worker

   php artisan queue:work


Caching Responses

To optimize performance and reduce redundant API calls, implement caching.

  1. 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));
   }


  1. 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.


Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration:
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn