Testing an API

I’m getting


The error pops up only after I enter a name & press the button in

The error is saying that the response is null (or at least doesn’t have an age element in the json object.
Some debug steps:

  • Take the string generated in the file_get_contents and put it in your browser bar and ensure it actually returns a value.
  • print_r $response to see if you get a value back
  • print_r $data to see the json object and ensure the age is set in the object.

Well actually its first saying that file_get_contents got a 505 back when trying to reach for the site on line 6, which is why line 10 fails.

urlencode the name. Also you might want to check agify’s API, i’m not sure its intended to take full names…

Just wanted to point out that using file_get_contents to access an api can work but it can lead to trouble as well. There are several libraries out there such as Guzzle or Symfony’s HttpClient that are specifically designed for this sort of thing. Might be worthwhile taking the time to learn how to use one.

2 Likes