REST APIs are the backbone of modern web development. Most web applications these days are developed as single-page applications on the frontend, connected to backend APIs written in various languages. There are many great frameworks that can help you build REST APIs quickly. Laravel/Lumen and Symfony’s API platform are the most often used examples in the PHP ecosystem. They provide great tools to process requests and generate JSON responses with the correct HTTP status codes. They also make it easy to handle common issues like authentication/authorization, request validation, data transformation, pagination, filters, rate throttling, complex endpoints with sub-resources, and API documentation. Show
You certainly don’t need a complex framework to build a simple but secure API though. In this article, I’ll show you how to build a simple REST API in PHP from scratch. We’ll make the API secure by using Okta as our authorization provider and implementing the Client Credentials Flow. Okta is an API service that allows you to create, edit, and securely store user accounts and user account data, and connect them with one or more applications. There are different authentication flows in OAuth 2.0, depending on if the client application is public or private and if there is a user involved or the communication is machine-to-machine only. The Client Credentials Flow is best suited for machine-to-machine communication where the client application is private (and can be trusted to hold a secret). At the end of the post, I’ll show you how to build a test client application as well. Table of Contents
Create the PHP Project Skeleton for Your REST APIWe’ll start by creating a
We’ve also configured a PSR-4 autoloader which will automatically look for PHP classes in the We can install our dependencies now: We now have a Let’s create a Next we’ll create a
and a We’ll need a
Configure a Database for Your PHP REST APIWe will use MySQL to power our simple API. We’ll create a new database and user for our app:
Our rest API will deal with just a single entity: Person, with the following fields:
We’ll add the database connection variables to our
Then we’ll input our local credentials in the .env file (which is not stored in the repo, remember?):
We can now create a class to hold our database connection and add the initialization of the connection to our bootstrap.php file:
Let’s create a
Our database is all set! If you want to reset it, just drop the Add a Gateway Class for the Person TableThere are many patterns for working with databases in an object-oriented context, ranging from simple execution of direct SQL statements when needed (in a procedural way) to complex ORM systems (two of the most popular ORM choices in PHP are Eloquent and Doctrine). For our simple API, it makes sense to use a simple pattern as well so we’ll go
with a Table Gateway. We’ll even skip creating a
Obviously, in a production system, you would want to handle the exceptions more gracefully instead of just exiting with an error message. Here are some examples of using the gateway:
Implement the PHP REST APIWe will implement a REST API now with the following endpoints:
We’ll create a
You can test the API with a tool like Postman. First, go to the project directory and start the PHP server:
Then connect to Secure Your PHP REST API with OAuth 2.0We’ll use Okta as our authorization server and we’ll implement the Client Credentials Flow. The flow is recommended for machine-to-machine authentication when the client is private and works like this: The client application holds a Client ID and a Secret; The client passes these credentials to Okta and obtains an access token; The client sends the access token to the REST API server; The server asks Okta for some metadata that allows it to verify tokens and validates the token (alternatively, it can just ask Okta to verify the token); The server then provides the API resource if the token is valid, or responds with a 401 Unauthorized status code if the token is missing, expired or invalid. Before you begin, you’ll need a free Okta developer account. Install the Okta CLI and run The Okta CLI will create an OAuth 2.0 Service App in your Okta Org. You will see output like the following when it’s finished:
Run
Your Okta domain is the first part of your issuer, before NOTE: You can also use the Okta Admin Console to create your app. See Create a Service App for more information. These are the credentials that your client application will need in order to authenticate. For this example, the client and server code will be in the same repository, so we will add these credentials to our Add to
Add these keys and values to
Log in to the Okta Admin Console (tip: run Add the scope to and the key with the value to Add Authentication to Your PHP REST APIWe’ll use the Okta JWT Verifier library. It requires a JWT library (we’ll use
Now we can add the authorization code to our front controller (if using a framework, we’ll do this in a middleware instead):
Build a Sample Client Application (Command Line Script) to Test the PHP REST APIIn this section, we will add a simple client application (a command line script using curl) to test the REST API. We’ll create a new php file ‘public/clients.php’ with a very simple flow: it will retrieve the Okta details (issuer, scope, client id and secret) from the .env file, then it will obtain an access token from Okta and it will run API calls to get all users and get a specific user (passing the Okta access token in the Authorization header).
You can run the application from the command line by going to the (Don’t forget to start the server if you haven’t already!)
That’s it! Learn More About PHP, Secure REST APIs, and OAuth 2.0 Client Credentials FlowYou can find all the code from this example on GitHub, in the oktadeveloper/okta-php-core-rest-api-example repository. If you would like to dig deeper into the topics covered in this article, the following resources are a great starting point:
Like what you learned today? Follow us on Twitter, and subscribe to our YouTube channel for more awesome content! API itu apa sih?API adalah mekanisme yang memungkinkan dua komponen perangkat lunak untuk saling berhubungan dengan menggunakan serangkaian definisi dan protokol. Misalnya, sistem perangkat lunak badan meteorologi, klimatologi, dan geofisika (BMKG) berisi data cuaca harian.
Apa itu API dan contohnya?API atau application programming interface adalah sebuah interface yang bisa menghubungkan dua atau lebih aplikasi secara bersamaan dan membuat pemrograman jauh lebih mudah. Contohnya, kode pemrograman ini dapat Anda terapkan untuk menghubungkan Booking Management Platform dengan perusahaan penyedia layanan.
Apa itu REST API PHP?Rest API adalah mekanisme yang memperbolehkan sebuah application atau device untuk dapat mengakses resource dari application atau device lain. Application atau device yang mengakses resource disebut client, sedangkan application atau device yang berisi resource adalah server.
Apa yang dimaksud dengan Web API?API adalah kepanjangan dari Application Programming Interface yang digunakan perangkat lunak untuk mengakses data, perangkat lunak server atau aplikasi lain dan telah ada selama beberapa waktu.
|