PHP REST API Tutorial: with PHP OOPS, PDO, UNIT Testing, JWT, CURD, EXAMPLES
What’s REST API or RESTFUL API?
REST is acronym for Representational State Transfer. Restful API is an architectural style for an application program interface (API) that uses HTTP requests to access and alter data. That data can be used to GET, PUT, POST and DELETE data types, which refers to the reading, updating, creating and deleting of operations concerning resources. For More Details
What’s JWT?
JWT stand for JSON Web Tokens, are an open, industry standard RFC 7519 method for representing claims securely between two parties. For details Click Here
If you want to play around with JWT token the here is your play ground
HOW JWT Token look like?
JWT Token has three parts these are
- 1 Header: ALGORITHM & TOKEN TYPE, identifies which algorithm is used to generate the signature, HS256 indicates that this token is signed using HMAC-SHA256. Typical cryptographic algorithms used are HMAC with SHA-256 (HS256) and RSA signature with SHA-256 (RS256). JWA (JSON Web Algorithms)
header = { "typ": "JWT", "alg": "HS256" }
- 2 Payload: Data, contains a set of claims. The JWT specification defines seven Registered Claim Names which are the standard fields commonly included in tokens.[1] Custom claims are usually also included, depending on the purpose of the token.
payload = { "id": 1, "user_name": "sapan", "email": "ctoattraveltech@gmail.com" }
- 3 Signature: VERIFY SIGNATURE, securely validates the token. The signature is calculated by encoding the header and payload using Base64url Encoding and concatenating the two together with a period separator. That string is then run through the cryptographic algorithm specified in the header, in this case HMAC-SHA256. The Base64url Encoding is similar to base64, but uses different non-alphanumeric characters and omits padding.
signature = HMACSHA256( base64UrlEncode(header) + "." + base64UrlEncode(payload), ) const token = base64urlEncoding(header) + '.' + base64urlEncoding(payload) + '.' + base64urlEncoding(signature)
Final token value is eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6MSwidXNlcl9uYW1lIjoic2FwYW4iLCJlbWFpbCI6ImN0b2F0dHJhdmVsdGVjaEBnbWFpbC5jb20ifQ.YuuHvX8IdNFugj0_1xiEbZ9f54PAnaExO9Xv_rjB4Rg
We will be creating a very simple REST API using
- PHP Programming Language with Object Oriented Concept
- PDO Library
- Mysql Database
- JWT Auth
- Unit Tetsing
Create a RESTful web service for a Book.
The service must have the following API endpoints:
- (C)reate a new Book
- (R)ead existing Books
- (U)pdate an existing Book
- (D)elete an existing Book
All test will perform using POSTMAN
Prerequisites
- PHP Installation
- Mysql Installation
- Composer Installation
- Local Apache Server UP
Rather than any individual installations you can use package installer which is really handy, like XAMPP and WAMP for windows, Lamp for linux.
You should have knowledge of PHP OOPS, to get started with the project that we are going to do.
Don’t be disappointed 💔 if you don’t know PHP, If you know any programming language that should be fine as well, COOL?
Let’s Go!
How to Start?
- Create Project folder ‘bookstore’
- Download Script from Github Repository to your project folder
- Go To Project Folder
cd bookstore
- UP the Mysql Server and create Database ‘rest-api’
- Run all below queries for newly Database ‘rest-api’
- RUN Below Command
Composer update
Wow, Now Your API endpoint is Ready For Test, If you want to understand about the implementation then go through the below section otherwise you can skip the below one.
Files and Folders
- config
- Database.php — file about database connectivity
- DatabaseImport.sql — sql import data — for migration
- test
CreateBook.php
- for test to create book functionalityReadBook.php
- for test to read book functionalityDeleteBook.php
- for test to delte book functionalityUpdateBokk.php
- for test to update book functionalityReadBookSingle.php
- for test to read book by id functionality- book.class.php — for controller, router
- index.php — for ping or endpoint
Basic testing done for all functions like create, update, read & delete book
This can be extend with more functionalities like input and output validation & parameters matching and sign-in proccess as well. Please consider this as task, complete the task and share it.
All this test conducted using HTTP_Request2 PEAR library.
Regarding HTTP_Request2 you can visit: https://pear.php.net/manual/en/package.http.http-request2.config.php
Ready to test, let’s go-ahead with testing using POSTMAN
All Requests and responses are JSON data
What all Endpoints are available for test?
- Sign-in for auth token - 'sign_in'
- (C)reate a new Book - 'create_book'
- (R)ead existing Books - 'read_book'
- (U)pdate an existing Book - 'update_book'
- (D)elete an existing Book - 'delete_book'
Open Your POSTMAN
- Create a Collection —
PHP REST API
- Single endpoint for all operation —
http://localhost/bookstore/
- Method Always has to be
POST
- Authentication Required for all requests apart of sign-in request
Lets test?
- Signin — fetch Auth Token for all requests, it need to send via request header
- Get Token Id on Successful Sign-in and pass to all other requests via their header
Create Book
Read Book
Read Book By Id
Update Book
Delete Book
I hope instructions are good to set up PHP REST API in your local, Enjoy Coding 👍