Create a REST API with PHP and Laravel
Tags: laravel, php, api, postman
Published: 2023-06-06 18:39:01


PHP came out in 1995, just three weeks after Java. Today, both remain in the top ten most popular languages. With PHP’s general ease of use, options for _how_ to use it abound. Yet, not every PHP tutorial is created equally. That’s why we put together this beginner-friendly [Postman Quickstarts tutorial](https://quickstarts.postman.com/guide/php-laravel-API/index.html?index=..%2F..index#0) on building a REST API with PHP. We’re using what we think is a straightforward framework for this purpose: Laravel. 

Laravel is a popular PHP web app framework that comes with a variety of built-in tools and features for building APIs. In this tutorial, we will be creating a simple API that allows users to add and retrieve data. 

## Before we get started…

Double check that you’re ready to write in PHP. Only a basic familiarity is needed for this tutorial, and PHP has a notoriously flat learning curve for new users—we encourage you to try at any skill level. 

Next, confirm that the following are installed:

* [Git](https://git-scm.com/downloads) (Required)
* [PHP](https://www.php.net/manual/en/install.php) (Required)
* [Composer](https://getcomposer.org/download/) (Required)
* [Homebrew](https://brew.sh/) (only for Mac)

If you want step by step instructions for installing any of the above, refer to the [full Laravel API quickstart guide at Postman.](https://quickstarts.postman.com/guide/php-laravel-API/index.html?index=..%2F..index#1) Plus, you’ll also want to open up your favorite code editor. Now, let’s get started!

## Step 1: Start your Laravel project

### Scaffold your Laravel project

Before we can write any code, we need to scaffold a [Laravel](https://laravel.com/) project. Thanks to Composer, this is relatively simple. Open a terminal and navigate to the directory where this project will live. Enter the following command in the terminal:

```bash
composer create-project laravel/laravel laravel_project
```

This could take some time. There are tens of megabytes to download and install.

When it's finished, you will have a project folder named `laravel_project`.


### Give it a test

Navigate into the `laravel_project` folder and enter the following command in the terminal:

```bash
php artisan serve --port=8080
```

This will launch your project at `http://localhost:8080`. Change the port to something else if you already have a process using the port. When it's running, visit the URL. It will return this homepage.

![Default Laravel project homepage](https://letmypeoplecode.com/wp-content/uploads/2023/06/laravel_initial.png)

Note down in the bottom right, you'll see the Laravel and PHP version numbers. If you're looking for tutorials, finding ones for Laravel and PHP that are as close to those versions as possible will help minimize problems.

Let's move on to adding an API.

## Step 2: Build an API

### Create the route

This will create a public API with no authentication.

Open `routes/api.php` in your Laravel project directory in your editor. Add the following code at the end:

```php
Route::get('/hello', function () {
  return "Hello World!";
});
```

This adds the `/api/hello` endpoint and returns "Hello World" in plain text to a GET request.

Note how the endpoint was prefixed with `/api` by Laravel.

Next, let's call this endpoint in Postman.

## Step 3: Try your first endpoint

To test this in Postman, open your personal workspace and start a collection. Name it "Laravel QuickStart" or something else you prefer.

Once it's created, select **Add a request** to get started.

![Adding a request to your Postman collection](https://letmypeoplecode.com/wp-content/uploads/2023/06/lv_pm_quickstart.png)


Set the request URL to `localhost:8080/api/hello` and make sure your Postman Desktop Agent app is running on your machine to prevent any CORS issues while testing locally.

Select **Send** and the response section below the request section will show a response of `Hello World!` in plain text with a `200 OK` response code.

![The result](https://letmypeoplecode.com/wp-content/uploads/2023/06/lv_pm_test1.png)

Congratulations. You created your first API endpoint in Laravel and successfully called it with Postman.

Next, let's make a simple POST endpoint for fun.

## Step 4: Add a POST endpoint

Go back to your `routes/api.php` file and add the following:

```php
Route::post('/reverse-me', function (Request $request) {
  $reversed = strrev($request->input('reverse_this'));
  return $reversed;
});
```

This adds a POST route for the endpoint `api/reverse-me`. It will reverse a string you pass in the body of the post with the parameter name `reverse_this`.

Let's try this in the next section.

## Step 5: Try your POST endpoint

Return to your Laravel QuickStart collection in Postman and add a request. Name it "Reverse" and follow these steps:

* Set the request type to `POST`.
* Set the endpoint to `localhost:8080/api/reverse-me`.
* Select the **Body** tab.
* In the top dropdown menu in the tab, select **x-www-form-urlencoded**.
* Add a parameter of `reverse_this` with the value of `esrever`. That's "reverse" already reversed so the return value will be easy to read.
* Select **Send**

![Result of reversing esrever](https://letmypeoplecode.com/wp-content/uploads/2023/06/lv_pm_test2.png)

The API will return the string reverse in plain text. Congratulations! You’ve created a REST API with PHP and Laravel.

## Summary

In this blog post, we explored how to create a simple PHP-based API with the Laravel framework. We created both GET and POST API endpoints and used Postman to test those endpoints. By following this tutorial, you should now have a solid understanding of how to create a basic API with Laravel and how to test it using Postman. 


## Going further…

If you want to deepen your knowledge of Laravel and Postman, try these exercises: 



* Dive into the [Laravel 10.x documentation](https://laravel.com/docs/10.x/) to add a controller for handling more complex requests and/or add a model to connect a database.
* Review the [Laravel 10.x error handling documentation](https://laravel.com/docs/10.x/errors) to learn best practices for error-handling in Laravel, such as what might happen if someone submitted a binary file instead of a string to your string-reversing endpoint.
* Explore the [Postman testing documentation](https://learning.postman.com/docs/writing-scripts/test-scripts/) and write a test on the POST request to make sure the reverse_this string is being reversed properly.

Check out [Postman Quickstarts](https://quickstarts.postman.com) for more step-by-step guides like this one. If you’d like to contribute your own, head over to the [Postman Quickstarts repo](https://github.com/loopDelicious/pmquickstarts) on GitHub.