Layman
Layman

Reputation: 1

Posting a JSON object to a REST API using PHP

I have found a couple of helpful links on stackoverflow but they haven't helped me complete my task because I am a complete beginner in trying to write PHP or use curl etc.

Send json post using php

Posting JSON data to API using CURL

I have been using Postman in Chrome to test API calls but I now want to put together a demo system on my Apache web server.

Does anyone have an example of a PHP webform posting to a json Object to a REST API?

Here is an example of what I want to send:

<?php
$url = "https://api.url/api/v1//accounts/create";
$jdata = json_encode($data);
$data = [{
  "status": "active",
  "username": ["uname"],
  "password": ["pword"],
  "attributes": {
    "forenames": ["fname"],
    "surname": ["lname"],
    "emailAddress": ["email"]
                 },
          }]
?>

Any advice would be fantastic. Like I said, I am new to curl and php, am unfamiliar with the array approach mentioned in the other articles and the ["info"] elements should be populated with the information filled in on my webform.

I hope I have been concise and explanitory but please let me know if you need anymore information.

Snook

Upvotes: 0

Views: 9579

Answers (1)

angelcool.net
angelcool.net

Reputation: 2546

Try something like the following, modifying steps 1 and 2 accordingly:

function sendRequest($data,$url)
{
    $postdata = http_build_query(array('data'=>$data));
    $opts = array('http' =>
      array(
          'method'  => 'POST',
          'header'  => "Content-type: application/x-www-form-urlencoded \r\n",
                       //"X-Requested-With: XMLHttpRequest \r\n".
                       //"curl/7.9.8 (i686-pc-linux-gnu) libcurl 7.9.8 (OpenSSL 0.9.6b) (ipv6 enabled)\r\n",
          'content' => $postdata,
          'ignore_errors' => true,
          'timeout' =>  10,
      )
    );
    $context  = stream_context_create($opts);
    return file_get_contents($url, false, $context);
}


// 1.- add your json
$data = '[{
    "status"      : "active",
    "username"    : ["uname"],
    "password"    : ["pword"],
    "attributes"  : {
        "forenames"   : ["fname"],
        "surname"     : ["lname"],
        "emailAddress": ["email"]
    },
}]';

// 2.- add api endpoint
$url= "https://api.url/api/v1//accounts/create"; 

// 3.- fire
$result = sendRequest($data,$url);

// 4.- dump result
echo $result;
die();

Good luck!!

Upvotes: 2

Related Questions