Klassroom presents the Techtalk: Scaling API with Laravel

09 May, 2020

I was invited to talk about Laravel API development and scaling on Muhammad Sumon Molla Selim's weekly web podcast Klassroom presents the Techtalk. We talked about a bunch of different things about API development for about 2 hours.

Here are the gist of my talk and various references on how to build and maintain a suntainable API in Laravel.

STEP 1

  • Just returning an array as response will make an API. Laravel's Response class implements Arrayable, Jsonable, ArrayObject and JsonSerializable interface. So, anything that implements these interface will return a json response.
  • Laravel Eloquent makes it even easier, just return any Model object or Collection, it will automatically cast it to json. Even it has built in feature to hide any specific column from the entity through $hidden attribute. It also protect us from mass assignment.
  • It has built in middlewares to take care of CORS, API throttling and other common issues.
  • Laravel has builtin auditing feature like created_at, updated_at timestamp, and it's very easy to add created_by, updated_by to your model.
  • Use proper HTTP response code and headers in your response.
  • Use proper HTTP verb and stick with one convention for for URL pattern.

STEP 2

  • You should never expose your database schema through API. You could use Laravel's API Resource to transform your Model response. For more control use something like league/fractal, or it's laravel bridge spatie/laravel-fractal for ease of use.
  • Don't expose your database IDs. Use generated complex id like uuid. You could use ramsey/uuid.
  • Do proper validation. Use laravel's validator, give proper validation error response.
  • Use Eloquent as long as it's serving your purpose, but don't hesitate to jump to SQL.
  • Consider your database a shared resource, even a single slow endpoint can make the whole API suite slower.
  • Use a profiler like blackfire.io or at least use barryvdh/laravel-debugbar.
  • Don't return the full model object where only a few column needed. Allow user to ask for the data they needed. You could use something like spatie/laravel-query-builder for that. You could also enable sorting feature by using spatie/eloquent-sortable package.
  • Always return paginated response while returning a Collection. If needed make an option to ask for the number of objects they needed.
  • Do not hard delete sensitive data, use soft delete instead.
  • Use a proper monitoring tool for your API like newrelic.

STEP 3

STEP 4

Enjoy!!