API with Laravel – 9/12/2023

HTTP methods

  1. GET – fetch/read data saja
  2. POST – create resource (data object) utk request
  3. PUT – utk update. biasa utk upload file
  4. PATCH – utk update. update some from all resources
  5. DELETE

sample of API end point.

verb / main resource (normally plural) / id

GET /products/12

headers, requests and response

  1. request
    1. conist of. headers and body
    2. all allowed http methods (GET, POST..)
    3. can contain parameters (data, body)
  2. response
    1. consist of headers and body
    2. uniformed output (json)
    3. http status code (success/ok 200, 400 not found, failed etc)
      1. reference: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status
  3. headers
    1. store/host all metadata including authentication key

Authentication

  1. basic auth – username and password, encoded with base64
    1. login page, user based auth
  2. api token – bearer token per user
    1. use case: login page, user based auth with abilities, mobile app
  3. api key – server generated token/key to auth
    1. in configuration file.
    2. app to api, api to api, backend comm, controlled env
  4. oauth 2.0 – combination of username/pass and token
    1. use case – login page, user-based auth with scopes, mobile app
  5. bearer auth – using bearer token under authorization header

authentication and authorization

  1. authentication – identify user legit or not
  2. authorization – apa scope yang dia boleh buat

laravel

  1. laravel sanctum – cover api token
  2. laravel passport – cover oauth 2.0

best practice

  1. atomic/singularity principle
    1. specific objective for every function
  2. follow standard and consistent naming conventions
    1. adheres to http method
    2. endpoint using nouns instead of verb
    3. response using json formatted structure
    4. uniformed response structure with appropriate status code
  3. using versioning to mitigate backward incompatibility
  4. always validate input and property handle errors
  5. capture errors in logs for easier troubleshoot/debug
  6. provide good support documentation (open api?)

laravel routes

  1. api – specific utk api
  2. web – utk web app

php artisan

  1. php artisan make:controller invoiceController –api
  2. php artisan route:list
  3. php artisan make:model Invoice –migration
  4. php artisan migrate

invoice

  1. InvoiceController, InvoiceCommand, InvoiceGateway

untuk postman, kena add header Accept application/json

GET hantar guna params

POST define dalam body

middleware = app/http/Kernel.php

X-API-KEY = if start with X, consider as custom param

CRUD, middleware

ways to consume API

php artisan make:controller InvoiceControler –resource

Leave a Reply

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