How to code a simple web API in 5 minutes with PHP
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
- Set headers for the response (e.g. the content type to return JSON)
- Use the built-in $_GET object to retrieve a query string parameter of the request
- Set up a custom response object
- Do some work; like retrieve a record from a MySQL database
- Encode the response object with json_encode into a JSON string ('echo' outputs a string/data)
- 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? 😅