title: Build API clients for PHP with Microsoft identity authentication description: Learn how use Kiota to build API clients in PHP to access APIs that require Microsoft identity authentication. author: Ndiritu ms.author: pgichuhi ms.topic: tutorial date: 03/20/2023
In this tutorial, you generate an API client that uses Microsoft identity authentication to access Microsoft Graph.
Run the following commands in the directory where you want to create a new project.
composer init
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.
- Authentication (Kiota default Azure authentication)
- HTTP (Kiota default Guzzle-based implementation)
- JSON serialization (Kiota default)
- Text serialization (Kiota default)
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-authentication-phpleague
composer require microsoft/kiota-serialization-json
composer require microsoft/kiota-serialization-text
Kiota generates API clients from OpenAPI documents. Create a file named get-me.yml and add the following.
:::code language="yaml" source="~/code-snippets/get-started/azure-auth/get-me.yml":::
You can then use the Kiota command line tool to generate the API client classes.
kiota generate -l PHP -d get-me.yml -c GraphApiClient -n GetUser\Client -o ./client
Add the following to your composer.json
to set your namespaces correctly:
"autoload": {
"psr-4": {
"GetUser\\Client\\": "client/"
}
}
To ensure the newly generated classes can be imported, update the autoload paths using:
composer dumpautoload
[!INCLUDE register-azure-app-auth-code-intro]
[!INCLUDE register-azure-app-auth-code-portal]
[!INCLUDE register-azure-app-auth-code-powershell]
Create a file in the root of the project named GetUser.php and add the following code. Replace the $clientId
and $clientSecret
with your credentials from the previous step.
[!INCLUDE get-azure-auth-code-manually]
Replace the $authorizationCode
with your authorization code.
:::code language="php" source="~/code-snippets/get-started/azure-auth/php/GetUser.php" id="ProgramSnippet":::
Note
This example uses the AuthorizationCodeContext class. You can use any of the credential classes from the kiota-authentication-phpleague
library.
To start the application, run the following command in your project directory.
php GetUser.php
- kiota-samples repository contains the code from this guide.
- ToDoItem Sample API implements a sample OpenAPI in ASP.NET Core and sample clients in multiple languages.