How to code a simple web API in 5 minutes with PHP

Kelvin Graddick · 1 minute read ·     

It often gets a bad rap, but PHP is a fast, flexible, and powerful server-side scripting language.

One of my favorite ways to use it is to quickly code web API endpoints.

How to code a simple web API in 5 minutes with PHP

  1. Set headers for the response (e.g. the content type to return JSON)
    • PHP response headers
  2. Use the built-in $_GET object to retrieve a query string parameter of the request
    • PHP query string argument
  3. Set up a custom response object
    • PHP response object
  4. Do some work; like retrieve a record from a MySQL database
    • PHP MySQL call
  5. Encode the response object with json_encode into a JSON string ('echo' outputs a string/data)
    • How to code a simple web API in 5 minutes with PHP
  6. A JSON payload will be returned with a status code 200

Pros of PHP

  • - Very low overhead to script/code and deploy
  • - Flexible and can quickly adapt to changes
  • - Easy to understand and learn
  • - Easy to test
  • - Free of cost and/or cheap to develop with

Cons of PHP

  • - Not scalable; if creating a large/complex API, use a PHP framework like Laravel, or other tech
  • - Language has inconsistencies which can lead to confusing code if not careful

⁉️ Have you used PHP for web dev before? Can you spot the security issue in this script? 😅

Want to share this?