Modifier

Partager via


Build API clients for PHP

In this tutorial, you build a sample app in PHP that calls a REST API that doesn't require authentication.

Required tools

Create a project

Run the following commands in the directory where you want to create a new project.

composer init

Project configuration

In case you're adding a Kiota client to an existing project, the following configuration is required:

  • composer.json > require > php set to "php": "^8.0 || ^7.4" or later.

Add dependencies

Before you can compile and run the generated API client, you need to make sure the generated source files are part of a project with the required dependencies. Your project must have a reference to the abstraction package. Additionally, you must either use the Kiota default implementations or provide your own custom implementations of the following packages.

For this tutorial, use the default implementations.

Run the following commands to get the required dependencies.

composer require microsoft/kiota-abstractions
composer require microsoft/kiota-http-guzzle
composer require microsoft/kiota-serialization-json
composer require microsoft/kiota-serialization-text

Generate the API client

Kiota generates API clients from OpenAPI documents. Create a file named posts-api.yml and add the following.

openapi: '3.0.2'
info:
  title: JSONPlaceholder
  version: '1.0'
servers:
  - url: https://jsonplaceholder.typicode.com/

components:
  schemas:
    post:
      type: object
      properties:
        userId:
          type: integer
        id:
          type: integer
        title:
          type: string
        body:
          type: string
  parameters:
    post-id:
      name: post-id
      in: path
      description: 'key: id of post'
      required: true
      style: simple
      schema:
        type: integer

paths:
  /posts:
    get:
      description: Get posts
      parameters:
      - name: userId
        in: query
        description: Filter results by user ID
        required: false
        style: form
        schema:
          type: integer
          maxItems: 1
      - name: title
        in: query
        description: Filter results by title
        required: false
        style: form
        schema:
          type: string
          maxItems: 1
      responses:
        '200':
          description: OK
          content:
            application/json:
              schema:
                type: array
                items:
                  $ref: '#/components/schemas/post'
    post:
      description: 'Create post'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/post'
      responses:
        '201':
          description: Created
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/post'
  /posts/{post-id}:
    get:
      description: 'Get post by ID'
      parameters:
      - $ref: '#/components/parameters/post-id'
      responses:
        '200':
          description: OK
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/post'
    patch:
      description: 'Update post'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/post'
      parameters:
      - $ref: '#/components/parameters/post-id'
      responses:
        '200':
          description: OK
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/post'
    delete:
      description: 'Delete post'
      parameters:
      - $ref: '#/components/parameters/post-id'
      responses:
        '200':
          description: OK

This file is a minimal OpenAPI description that describes how to call the /posts endpoint in the JSONPlaceholder REST API.

You can then use the Kiota command line tool to generate the API client classes.

kiota generate -l PHP -d ../posts-api.yml -c PostsApiClient -n KiotaPosts\Client -o ./client

Tip

Add --exclude-backward-compatible if you want to reduce the size of the generated client and are not concerned about potentially source breaking changes with future versions of Kiota when updating the client.

Add the following to your composer.json to set your namespaces correctly:

"autoload": {
    "psr-4": {
        "KiotaPosts\\Client\\": "client/"
    }
}

To ensure the newly generated classes can be imported, update the autoload paths using:

composer dumpautoload

Create the client application

Create a file in the root of the project named main.php and add the following code.

<?php

use KiotaPosts\Client\PostsApiClient;
use KiotaPosts\Client\Models\Post;
use Microsoft\Kiota\Abstractions\ApiException;
use Microsoft\Kiota\Abstractions\Authentication\AnonymousAuthenticationProvider;
use Microsoft\Kiota\Http\GuzzleRequestAdapter;

require __DIR__.'/vendor/autoload.php';

try {
    $authProvider = new AnonymousAuthenticationProvider();
    $requestAdapter = new GuzzleRequestAdapter($authProvider);
    $client = new PostsApiClient($requestAdapter);

    // GET /posts
    $allPosts = $client->posts()->get()->wait();
    $postCount = sizeof($allPosts);
    echo "Retrieved {$postCount} posts.\n";

    // GET /posts/{id}
    $specificPostId = 5;
    $specificPost = $client->posts()->byPostId($specificPostId)->get()->wait();
    echo "Retrieved post - ID: {$specificPost->getId()}, Title: {$specificPost->getTitle()}, Body: {$specificPost->getBody()}\n";

    // POST /posts
    $newPost = new Post();
    $newPost->setUserId(42);
    $newPost->setTitle("Testing Kiota-generated API client");
    $newPost->setBody("Hello world!");

    $createdPost = $client->posts()->post($newPost)->wait();
    echo "Created new post with ID: {$createdPost->getId()}\n";

    // PATCH /posts/{id}
    $update = new Post();
    // Only update title
    $update->setTitle("Updated title");

    $updatedPost = $client->posts()->byPostId($specificPostId)->patch($update)->wait();
    echo "Updated post - ID: {$updatedPost->getId()}, Title: {$updatedPost->getTitle()}, Body: {$updatedPost->getBody()}\n";

    // DELETE /posts/{id}
    $client->posts()->byPostId($specificPostId)->delete()->wait();
}catch (ApiException $ex) {
    echo $ex->getMessage();
}
?>

Note

The JSONPlaceholder REST API doesn't require any authentication, so this sample uses the AnonymousAuthenticationProvider. For APIs that require authentication, use an applicable authentication provider.

Run the application

To start the application, run the following command in your project directory.

php main.php

See also