Heim  >  Artikel  >  Backend-Entwicklung  >  SharpAPI Laravel-Integrationshandbuch

SharpAPI Laravel-Integrationshandbuch

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-07 06:07:29690Durchsuche

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.


Das obige ist der detaillierte Inhalt vonSharpAPI Laravel-Integrationshandbuch. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn