Creating an API with Lithe

Lithe - Oct 17 - - Dev Community

If you're interested in building a simple API using Lithe, you've come to the right place! In this tutorial, we'll step by step create an API that allows sending and receiving messages in a chat. We'll use routers to organize our code modularly.

What You Will Learn

  • Set up a PHP project with Lithe.
  • Create a router to manage chat messages.
  • Implement basic functionalities such as sending and receiving messages.
  • Test the API using Postman or Insomnia.

Prerequisites

  • Basic knowledge of Lithe and PHP.
  • A PHP development environment installed (with Composer).
  • A code editor (I recommend Visual Studio Code).

Installing Lithe

To create a new project with Lithe, run the following command:

composer create-project lithephp/lithephp chat-api
Enter fullscreen mode Exit fullscreen mode

Project Structure

Create the following directory and file structure within the chat-api directory:

chat-api/
│
├── src/
│   ├── routes/
│   │   └── chat.php
│   └── App.php
└── composer.json
Enter fullscreen mode Exit fullscreen mode

Starting the Application

In the src/App.php file, configure the application with the following code:

<?php 
use function Lithe\Orbis\Http\Router\{router};

$app = new \Lithe\App;

// Router to manage chat messages
$chatRoutes = router(__DIR__ . '/routes/chat');

$app->use('/api/chat', $chatRoutes);

$app->listen();
Enter fullscreen mode Exit fullscreen mode

Creating the Routes File

In the src/routes directory, create the chat.php file to manage the routes related to the chat. Add the following code:

use function Lithe\Orbis\Http\Router\{get, post};

// Array to store messages
$messages = [];

// Route to get all messages
get('/', function ($req, $res) use (&$messages) {
    $res->json($messages);
});

// Route to send a new message
post('/', function ($req, $res) use (&$messages) {
    $user = $req->input('user');
    $text = $req->input('text');

    if (!$user || !$text) {
        return $res->status(400)->json(['error' => 'User and text are required']);
    }

    $timestamp = (new DateTime())->format('Y-m-d H:i:s');

    $message = compact('user', 'text', 'timestamp');
    $messages[] = $message;

    $res->status(201)->json($message);
});
Enter fullscreen mode Exit fullscreen mode

Testing the API

Now that your API is set up, let's test it using a tool like Postman or Insomnia.

1. Start the Server

In the terminal, run the following command to start the server:

php line serve
Enter fullscreen mode Exit fullscreen mode

You will see the message Server running on port 8000.

2. Test the Messages Route

2.1 Get All Messages

  1. Open Postman.
  2. Create a new GET request to http://localhost:8000/api/chat.
  3. Click Send. You should see an empty array initially [].

2.2 Send a New Message

  1. Create a new POST request to http://localhost:8000/api/chat.
  2. Go to the Body tab and select the raw option. Choose the JSON type.
  3. Add the following JSON in the body of the request:
{
    "user": "William",
    "text": "Hello, how is everyone?"
}
Enter fullscreen mode Exit fullscreen mode
  1. Click Send. You should receive the sent message as a response:
{
    "user": "William",
    "text": "Hello, how is everyone?",
    "timestamp": "2023-10-17 15:30:00"
}
Enter fullscreen mode Exit fullscreen mode

3. Check All Messages

Make another GET request to http://localhost:8000/api/chat. You should see the message you just sent:

[
    {
        "user": "William",
        "text": "Hello, how is everyone?",
        "timestamp": "2023-10-17 15:30:00"
    }
]
Enter fullscreen mode Exit fullscreen mode

Conclusion

Congratulations! You have created a simple chat API using Lithe. This API can be expanded with functionalities such as user authentication, data persistence in a database, and much more.

Next Steps

  • Data Persistence: Use a database like MySQL or PostgreSQL to store messages permanently.
  • Authentication: Add authentication so that only authenticated users can send messages.
  • WebSockets: Explore using WebSockets to enable real-time communication.

Feel free to share your ideas and improvements in the comments! If you enjoyed this tutorial, consider leaving a reaction and sharing it with other developers.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .