SharpAPI Laravel 統合ガイド

Mary-Kate Olsen
リリース: 2024-10-07 06:07:29
オリジナル
689 人が閲覧しました

SharpAPI Laravel Integration Guide

SharpAPI Laravel 統合ガイド へようこそ!このリポジトリは、SharpAPI を次の Laravel AI アプリケーションに統合する方法に関する包括的なステップバイステップのチュートリアルを提供します。 ** AI を活用した機能** でアプリを強化したい場合でも、ワークフローを自動化する場合でも、このガイドでは、認証から API 呼び出しの実行と応答の処理までのプロセス全体を説明します。

記事は https://github.com/sharpapi/laravel-ai-integration-guide で Github リポジトリとしても公開されています。


目次

  1. 前提条件
  2. Laravel プロジェクトのセットアップ
  3. SharpAPI PHP クライアントのインストール
  4. 構成
    • 環境変数
  5. SharpAPI による認証
  6. API呼び出しの実行
    • 例: 職務記述書の生成
  7. 応答の処理
  8. エラー処理
  9. 統合のテスト
  10. 高度な使用法
    • 非同期リクエスト
    • 応答のキャッシュ
  11. 結論
  12. サポート
  13. ライセンス

前提条件

始める前に、次の要件を満たしていることを確認してください:

  • PHP: >= 8.1
  • Composer: PHP の依存関係マネージャー
  • Laravel: バージョン 9 以降
  • SharpAPI アカウント: SharpAPI.com から API キーを取得します。
  • Laravel の基礎知識: Laravel フレームワークと MVC アーキテクチャに関する知識

Laravelプロジェクトのセットアップ

Laravel プロジェクトがすでにある場合は、このステップをスキップできます。それ以外の場合は、次の手順に従って新しい Laravel プロジェクトを作成します。

  1. Composer 経由で Laravel をインストールします

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


ログイン後にコピー
  1. プロジェクト ディレクトリに移動します

   cd laravel-ai-integration-guide


ログイン後にコピー
  1. アプリケーションを提供する

   php artisan serve


ログイン後にコピー

アプリケーションは http://localhost:8000 でアクセスできます。


SharpAPI PHP クライアントのインストール

SharpAPI と対話するには、SharpAPI PHP クライアント ライブラリをインストールする必要があります。

Composer 経由で SharpAPI パッケージが必要です


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


ログイン後にコピー

構成

環境変数

API キーなどの機密情報を環境変数に保存することがベスト プラクティスです。 Laravel は、環境固有の構成に .env ファイルを使用します。

  1. .env ファイルを開きます

Laravel プロジェクトのルート ディレクトリにあります。

  1. SharpAPI API キーを追加します

   SHARP_API_KEY=your_actual_sharpapi_api_key_here


ログイン後にコピー

: your_actual_sharpapi_api_key_here を実際の SharpAPI API キーに置き換えます。

  1. コードでの環境変数へのアクセス

Laravel は、環境変数にアクセスするための env ヘルパー関数を提供します。


   $apiKey = env('SHARP_API_KEY');


ログイン後にコピー

SharpAPIによる認証

SharpAPI のエンドポイントと安全にやり取りするには認証が必要です。

  1. SharpAPI クライアントを初期化します

サービスを作成するか、コントローラーで直接使用します。


   <?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. サービスプロバイダーでのサービスのバインド (オプション)

これにより、必要な場所にサービスを挿入できます。


   <?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. コントローラーでのサービスの使用

   <?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. ルートの定義

ルートをroutes/web.phpまたはroutes/api.phpに追加します:


   use App\Http\Controllers\SharpApiController;

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


ログイン後にコピー

API呼び出しの実行

認証されると、さまざまな SharpAPI エンドポイントへの API 呼び出しを開始できるようになります。以下は、さまざまなエンドポイントと対話する方法の例です。

例: 職務記述書の生成

  1. ジョブ記述パラメータ 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. ルートを定義します

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


ログイン後にコピー
  1. エンドポイントへのアクセス

生成されたジョブの説明を確認するには、http://localhost:8000/sharpapi/generate-job-description にアクセスしてください。


応答の処理

SharpAPI 応答は通常、ジョブ オブジェクトにカプセル化されます。これらの応答を効果的に処理するには:

  1. 応答構造を理解する

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


ログイン後にコピー
  1. 結果へのアクセス

提供されたメソッドを使用して結果データにアクセスします。


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


以上がSharpAPI Laravel 統合ガイドの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

ソース:dev.to
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
著者別の最新記事
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!