Currently Available: Need a skilled Software Developer for your next project?
Categories
Laravel

Building REST APIs in Laravel with API Platform

When you need a REST API for a Laravel project, API Platform can generate endpoints and API documentation from metadata on your Eloquent models. That metadata describes a model's role in the API and lists the operations clients can use to read or change it. API Platform reads those definitions and connects the API to Laravel and Eloquent.

You can get a basic API running quickly this way, because the Laravel integration already handles pagination, filtering, validation, and authorization. Even so, you still have to decide which data and operations belong in your public API. Start with one resource, inspect what API Platform exposes, and then add only the fields and behavior your clients need.

Install API Platform and expose a model

In an existing Laravel project, install the package and run its installer:

composer require api-platform/laravel
php artisan api-platform:install

Create and migrate your Eloquent model before you expose it. Because API Platform reads database schema details, including column types and relationships, it needs the migrated tables to build resource metadata. Add the ApiResource attribute to the model:

namespace App\Models;

use ApiPlatform\Metadata\ApiResource;
use Illuminate\Database\Eloquent\Model;

#[ApiResource]
class Book extends Model
{
}

Once the migration has run, start Laravel with php artisan serve and inspect the API under /api/. The Laravel integration documentation covers the installation options and the generated API documentation.

If you do not specify operations, API Platform registers the standard CRUD operations: collection GET and POST for working with book lists, and item GET, PATCH, and DELETE for working with a single book. It does not register PUT by default. With those defaults, clients can list books, create a book, fetch one book, partially update it, and delete it. If you list operations explicitly on a resource, you must include every operation you want to keep, because API Platform drops any unspecified defaults. The operations documentation shows how to configure that list.

Before you expose a resource, decide whether clients should be able to write to it. For a read-only book catalog, declare only collection and item GET operations. When you limit the declared operations, you keep the API surface aligned with its intended use and avoid granting write access because the model happens to support it.

Inspect the generated response and documentation

API Platform generates OpenAPI documentation from resource metadata to describe the available operations and their parameters. Client developers can browse that documentation in interfaces such as Swagger UI and ReDoc. You should also check the response format, since JSON-LD is the default format. API Platform supports other configured formats as well, including JSON:API and CSV.

Confirm the format and media type your clients expect before they depend on the API. A client that expects plain JSON may not handle a JSON-LD response the same way. Check the generated documentation and send a representative request so you can verify both the response body and the content type.

Add pagination and a focused filter

API Platform paginates collection responses by default, returning 30 items per page. You can set a smaller page size on a resource by adding paginationItemsPerPage: 10 to its metadata. Pick a page size that matches how much data clients need at once, and confirm that your clients follow the pagination links or parameters in the response.

Filters let clients narrow a collection by specific fields. Declare a query parameter for a concrete need, such as partial matching on a book title, instead of making every model column searchable. Once you configure a title parameter, a client can request /api/books?title=laravel. API Platform can include configured parameters in its generated documentation and validate them. See the Laravel filters documentation for the supported filter types.

Clients that consume paginated responses also need to request subsequent pages when they want the full collection. For that client-side work, see handling paginated API responses.

Connect Laravel validation and authorization

Laravel validation rules and Form Requests work with API Platform. A Form Request is a Laravel request class that holds validation rules. The integration can detect a Form Request with the expected name, or it can use one you specify in resource metadata. Add rules for the fields clients can submit, then test both valid and invalid input.

API Platform returns different HTTP status codes depending on why the input failed. Starting with API Platform 4.4, it returns HTTP 422 for certain request-body type mismatches when an applicable Laravel validation rule exists. When no matching rule exists, API Platform returns the original deserialization error as HTTP 400. The Laravel validation documentation details this version-specific behavior.

Authentication identifies the caller, while authorization decides whether that caller can perform an action. API Platform maps resource operations to Laravel policy methods: collection GET to viewAny, item GET to view, POST to create, PATCH to update, and DELETE to delete. You can also apply Laravel middleware such as auth:sanctum to individual operations or set it as a default. Configure the policy for the data and actions each resource exposes, then test that unauthorized requests fail. The Laravel security documentation covers middleware, policies, and gates.

Use a separate API representation when CRUD no longer fits

An Eloquent model describes how Laravel stores data, while a public API resource describes what clients can see and do. Those two shapes can start out alike, but they often diverge when an endpoint needs to hide internal fields, combine data from several models, or run a business action instead of updating a single record.

API Platform supports data-transfer objects (DTOs), custom state providers, and processors for those cases. A provider supplies data for a resource, and a processor handles a change requested by a client. For example, an operation that submits an order may need to check inventory and create related records instead of directly updating an Order model. When you put that behavior in a custom processor, the API represents the action without exposing database details as its contract.

Test the contract and prepare deployment

Test the behavior your clients depend on, including response fields, status codes, validation failures, policy denials, filters, pagination, and custom operations. API Platform documents Laravel API testing with both Pest and PHPUnit in its testing documentation. You cannot rely on a database write test alone to confirm that the API returns the right representation or rejects an unauthorized request.

Plan for database access during builds and deployment. Because API Platform reads the schema while building resource metadata, Laravel startup and commands such as route or OpenAPI generation may require a reachable database with migrations applied. If a CI job runs those commands without a database, it can fail before your tests even start.

The Laravel documentation describes two ways to build without access to the production database. You can generate and package a metadata dump while a database is available, or you can provide a migrated SQLite database during the build or analysis. Generate a new metadata dump whenever your resource code or schema changes. In production, API Platform uses Laravel's cache system for metadata when APP_DEBUG is false. The documentation recommends running php artisan optimize and php artisan optimize:clear. Measure the deployed application to see how caching affects its speed.

Check package compatibility

As of November 22, 2026, Packagist lists api-platform/laravel v5.0.9 with PHP 8.2 or higher and Laravel 11, 12, or 13 among its requirements. Laravel 13 has its own higher PHP requirement, so the package minimum does not apply to every Laravel version combination. Check the resolved versions in your project's Composer lock file and the current package requirements before upgrading, because the Laravel guide's release-specific compatibility statements do not fully reflect the newer v5 package metadata.

What I'm building

Delegate tasks. Get software.

Give Vroni a GitHub issue, bug report, spec, or rough idea. It reads the repo, plans the change, writes code, runs checks, and works toward a review-ready pull request.

Take a look at vroni.com

Email updates

Usually a new article and a few links I found interesting.

No spam. Unsubscribe with one click.

Leave a Reply

Your email address will not be published. Required fields are marked *