Building an Account Management API with Utopia PHP


In this tutorial, we will walk through the process of creating a basic API for account management using the Utopia PHP framework. We will cover user registration, user login, and fetching user details functionalities. By the end of this tutorial, you'll have a foundation for building more complex account management systems.

Prerequisites

Before we begin, make sure you have the following:

  • Utopia PHP framework installed. You can install it using Composer by running the command composer require utopia-php/framework.

  • A web server with PHP 8.0 or later.

Setting up the Utopia PHP Application

  1. Create a new directory for your project and navigate into it.

  2. Initialize a new PHP file, e.g., index.php, and require the Utopia PHP autoloader:

<?php

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

use Utopia\App;
use Utopia\Request;
use Utopia\Response;
  1. Create a new instance of the App class and initialize the request and response objects:
$app = new App('America/New_York');
$request = new Request();
$response = new Response();

User Registration Endpoint

Let's start by implementing the user registration functionality.

  1. Add the following code to handle the user registration endpoint:
$app->post('/register')
    ->inject('request')
    ->inject('response')
    ->action(function($request, $response) {
        $data = $request->getPayload();

        // Validate the input data

        // Perform user registration logic

        // Send the response
    });
  1. Inside the action function, we'll first validate the input data. In this example, we'll validate the name, email, and password fields using Utopia's built-in validators:
$nameValidator = new Text(2, 100);
$emailValidator = new Email();
$passwordValidator = new Text(6);

if (!$nameValidator->isValid($data['name'])) {
    $response->json(['error' => 'Invalid name']);
    return;
}

if (!$emailValidator->isValid($data['email'])) {
    $response->json(['error' => 'Invalid email']);
    return;
}

if (!$passwordValidator->isValid($data['password'])) {
    $response->json(['error' => 'Invalid password']);
    return;
}
  1. Once the data is validated, you can proceed with the user registration logic. This could involve storing the user details in a database, generating a unique user ID, etc. Modify the code according to your specific implementation.

  2. Finally, send the appropriate response indicating the success or failure of the registration process:

$response->json(['message' => 'User registered successfully']);

User Login Endpoint

Next, let's implement the user login functionality.

  1. Add the following code to handle the user login endpoint:
$app->post('/login')
    ->inject('request')
    ->inject('response')
    ->action(function($request, $response) {
        $data = $request->getPayload();

        // Validate the input data

        // Perform user login logic

        // Send the response
    });
  1. Similar to the registration endpoint, validate the input data (email and password) using the appropriate validators:
$emailValidator = new Email();
$passwordValidator = new Text(6);

if (!$emailValidator->isValid($data

['email'])) {
    $response->json(['error' => 'Invalid email']);
    return;
}

if (!$passwordValidator->isValid($data['password'])) {
    $response->json(['error' => 'Invalid password']);
    return;
}
  1. Proceed with the user login logic, such as verifying the user's credentials, generating an authentication token, etc. Adjust the code to match your desired login process.

  2. Finally, send the response indicating the success or failure of the login attempt:

$response->json(['message' => 'User logged in successfully']);

Fetching User Details

Lastly, let's implement the endpoint to fetch user details.

  1. Add the following code to handle the user details endpoint:
$app->get('/user/{userId}')
    ->inject('request')
    ->inject('response')
    ->action(function($request, $response, $userId) {
        // Perform user lookup logic

        // Send the response
    });
  1. Inside the action function, retrieve the user details based on the provided userId. This could involve querying a database, fetching user information, and constructing an array representing the user.
$user = [
    'id' => $userId,
    'name' => 'John Doe',
    'email' => 'john@example.com',
    // Additional user details
];
  1. Finally, send the response with the user details in JSON format:
$response->json($user);

Running the Application

To run the application, add the following code at the end of your index.php file:

App::setMode(App::MODE_TYPE_PRODUCTION);
$app->run($request, $response);

Now, start your web server and navigate to the appropriate URL to access the API endpoints you've just created.

Congratulations! You've successfully built a basic API for account management using the Utopia PHP framework. Feel free to expand on this foundation and customize it according to your specific project requirements.


That's it! You now have a step-by-step guide for building an API for account management using the Utopia PHP framework. Remember to modify the code as needed for your specific use case and explore the Utopia PHP documentation for more advanced features and functionalities.

if this post helped you please share, Happy coding!