DEV Community

Nachiket Panchal
Nachiket Panchal

Posted on • Originally published at errorsea.com on

3 1

How to Create a Simple PHP REST API

REST(RESTful) API is the most used method of data transfer. However, there are several other ways to transfer data transfer, but REST is popular among them, so let’s know a little bit about REST APIs.

What is the REST API?

REST API is known as RESTful API is a universal method of data transfer, and it becomes more popular due to its flexibility.

It returns data in JSON format which is supported by all languages. REST API can be integrated with all development platforms.

Here we are going to discuss how to create a simple REST API in Core PHP.

REST API in PHP

PHP is a popular back-end language in web programming. In addition, it can handle simple to complex APIs. Let’s look at an example about REST API in Core PHP.

PHP has an inbuilt function json_encode() to convert PHP objects into JSON format.

Example

<?php
$object = ['Name' => 'Nachiket Panchal', 'Link' => 'errorsea.com', 'data' => ['Key1' => 'Value1', 'Key2' => 'Value2', 'Key3' => 'Value3']];
header("content-type: application/json");
echo json_encode($object); ?>

Enter fullscreen mode Exit fullscreen mode

Explanation

  • First, we define a PHP object named $object.
  • Next, we set a header of content-type: application/json to provide content information to the receiver.
  • Finally, we convert our $object variable into json with json_encode() function and echo it.

We can also use a database to create a dynamic API for high-end application development.

Conclusion

We have now learned the most basic REST API development using PHP. We can also develop a more advanced API using PHP.

The post How to Create a Simple PHP REST API appeared first on errorsea.

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (1)

Collapse
 
sudhiryadav profile image
Sudhir Yadav

the echo, print and print_r all returns JSON appended by square bracket in the end. Any way to remove it? Ex:

{
"a":"aval",
"b":"bval"
}[]

Look at the last square bracket

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay