как работать с API
Как взаимодействовать с API посредством PHP , есть адрес нужно методом POST Отправить на него пустой или с параметрами запрос , который отдаст результат , как вообще и каким средствами это делается ?
Отслеживать
задан 24 апр 2019 в 13:31
user335973 user335973
11 1 1 бронзовый знак
средствами php. Задайте конкретный вопрос!
24 апр 2019 в 13:36
@Dmitriy примеры коды что бы отправить POST запрос и получить ответ
24 апр 2019 в 13:43
ну POST запрос на php можно отправить 3-мя способами. Через сокет, через curl, или хитро через file_get_content()
24 апр 2019 в 13:46
@Dmitriy примеры можно ? и какой способ на ваш взгляд предпочтительнее ?
24 апр 2019 в 13:47
если ни разу не отправляли проще всего curl`ом
24 апр 2019 в 13:51
1 ответ 1
Сортировка: Сброс на вариант по умолчанию
$url = "http://myapi.com"; $post_data = array ( "foo" => "bar", "query" => "Nettuts", "action" => "Submit" ); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // указываем, что у нас POST запрос curl_setopt($ch, CURLOPT_POST, 1); // добавляем переменные curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data); $output = curl_exec($ch); curl_close($ch); echo $output;
в $url адрес вашего API
в $post_data параметры массивом (Имя => значение)
в $output получите ответ
Отслеживать
ответ дан 24 апр 2019 в 13:57
884 12 12 серебряных знаков 29 29 бронзовых знаков
Если нужно без параметров post_data отставлять пустой ? Вида? : $post_data = array ( «» => «», «» => «», «» => «» );
24 апр 2019 в 14:02
@user335973 Нет вот эту строку удалить curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data); Ну и $post_data не нужен
How to Use an API with PHP (Complete Beginner’s Guide)

PHP gained fame as easy to learn and at the same time quite powerful programming language.
Throughout its history, it went through several periods of ups and downs, but with the release of the seventh version, PHP confidently returns lost positions and firmly holds the title of one of the most popular languages for web development.
An important part of many web apps is the interaction with external APIs to obtain the necessary data and extend the capabilities of the application. PHP provides a rich set of functions to work with APIs, and we will discuss these functions in more detail in this article.
Overview of cURL
To work with the APIs, we will use cURL and a free app that allows making HTTP requests in PHP.
The cURL project offers two sub-projects:
- cURL — command-line tool for sending HTTP requests from the terminal. For example, curl -X GET https://www.google.com/ command sends a GET request to the Google server, and if everything is alright, the server will send the contents of the search page in response. curl is a wrapper for libcurl.
- libcurl — transfer library that developers can embed in their programs. It’s very common for PHP to use this library.
Prerequisites to start using API with PHP
To get started we will need PHP itself, so we will install it, as well as the php-curl library.
To do this, type this command in the terminal (we use Ubuntu Linux. If you’re using another OS, the commands may differ):
sudo apt install php php-curl
Request Methods with PHP and cURL
Types of Requests or Request Methods characterize what action we are going to take by calling the API.
There are four main types of actions in total:
- GET: retrieve information (like product information). This is the most common type of request. By using it, we can get the data we are interested in from API.
- POST: adds new data to the server. By using this type of request you can, for example, add a new review of a hotel.
- PUT: changes existing information. For example, by using this type of request, it would be possible to change the text and publication date in an existing blog post.
- DELETE: deletes existing information
What are API Endpoints?
In order to work with APIs through request methods, it is also important to understand the endpoint concept.
Usually, an endpoint refers to a specific address (for example, https://best-tours.com/best-tours-prague). By referring to this address (with certain request method) you get access to certain features/data. In our case – the list of best tours to Prague. Commonly, the name (address) of the endpoint corresponds to the functionality it provides.
Request Method Examples on RapidAPI
To demonstrate the implementation of Request Methods in PHP, we will look at simple API example within the RapidAPI service. This service is an API Hub providing the ability to access thousands of different APIs. Another advantage of RapidAPI is that you can access endpoints and test the work of the API directly in its section within the RapidAPI service.
Let’s try using the KVStore API. This API is used for storage and handling of simple data, such as user form submissions.

How to find APIs on RapidAPI.com
In order to find KVStore API section:
- enter its name in the search box in the RapidAPI service
- or go to “Data” category from “All Categories” list and select this API from the list.
Browse APIsThis API works under freemium conditions, allowing to store a limited amount of data for free, but for our purposes, it will be enough.

Once you select KVStore API, the first page you’ll see is the API Endpoints subsection. This includes most of the information needed to get started. The API Endpoints subsection includes navigation, a list of endpoints, the documentation of the currently selected endpoint, and a code snippet (available in 8 different programming languages) to help you get started with your code.

Once the required API is found, and we can begin to work. We will go through Request Methods (GET POST PUT DELETE) by completing the following steps:
- Make a POST request for the API to create a collection of data.
- Make a GET request where we will use the collection name from the first step, thereby demonstrating GET requests and the fact that the collection was created.
- Make a PUT request where we substitute the modified object and demonstrate the answer.
- Make a DELETE request with the collection name and show the answer.
- Make a GET request with the collection name again to show that the DELETE method worked and there is no collection with such a name.
To get started with this API, we need to call Sign Up endpoint:

1. Make a POST Request
Now we go to the first step and create a collection of data using the Create Collection endpoint. Firstly we need to specify the URL to which we will make a request.
// kvstore API url $url = 'https://kvstore.p.rapidapi.com/collections';
Next, let’s create an object that we will send to the server to create a collection. Here we show that we want to create a collection named RapidAPI:
// Collection object $data = [ 'collection' => 'RapidAPI' ];
Now, we create a new cURL session using the curl_init method and immediately link it to our URL:
// Initializes a new cURL session $curl = curl_init($url);
Our session needs to be configured. For example, we need to specify the type of request, the request body, the necessary headers, etc.
// 1. Set the CURLOPT_RETURNTRANSFER option to true curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); // 2. Set the CURLOPT_POST option to true for POST request curl_setopt($curl, CURLOPT_POST, true); // 3. Set the request data as JSON using json_encode function curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data)); // 4. Set custom headers for RapidAPI Auth and Content-Type header curl_setopt($curl, CURLOPT_HTTPHEADER, [ 'X-RapidAPI-Host: kvstore.p.rapidapi.com', 'X-RapidAPI-Key: [Input your RapidAPI Key Here]', 'Content-Type: application/json' ]);
Let’s take a closer look at what we did in the code snippet above. The curl_setopt method accepts a session handle returned by curl_init , the parameter we want to configure, and the value for the parameter
- In the first case, we set CURLOPT_RETURNTRANSFER parameter to true. It will be necessary for the future, with the help of this setting we will force the curl_exec method to return us the answer from the server as a string.
- In the second case, we set CURLOPT_POST to true and thereby say that we want to make a POST request
- In the third case, we add a body to our request, but before that, we need to translate it into the necessary format, so here we make a JSON string from the object
- In the fourth – we write all the necessary headers for the request
After we have prepared our cURL session, we call curl_exec and pass into it the cURL session descriptor that needs to be executed with all the settings set. And since we previously set the value CURLOPT_RETURNTRANSFER to true, curl_exec will return a response from the server, which we will save in the $response variable.
// Execute cURL request with all previous settings $response = curl_exec($curl);
Next, we need to close the session:
// Close cURL session curl_close($curl);
And also display the response from the server:
echo $response . PHP_EOL;
As a result, we obtain the following file:
'RapidAPI' ]; // Initializes a new cURL session $curl = curl_init($url); // Set the CURLOPT_RETURNTRANSFER option to true curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); // Set the CURLOPT_POST option to true for POST request curl_setopt($curl, CURLOPT_POST, true); // Set the request data as JSON using json_encode function curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data)); // Set custom headers for RapidAPI Auth and Content-Type header curl_setopt($curl, CURLOPT_HTTPHEADER, [ 'X-RapidAPI-Host: kvstore.p.rapidapi.com', 'X-RapidAPI-Key: 7xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', 'Content-Type: application/json' ]); // Execute cURL request with all previous settings $response = curl_exec($curl); // Close cURL session curl_close($curl); echo $response . PHP_EOL;
If we run it, we should get this response:
It seems that everything is OK!
Note: In order to run files with the above code, you can simply run php in the command line.
2. Make the GET Request
Now we will execute a GET request to get data from the server. Most of the parameters will be similar to those specified in the previous step.
According to the documentation in order to get a collection of data, we need to specify its name by adding it to the URL:
$url = 'https://kvstore.p.rapidapi.com/collections'; $collection_name = 'RapidAPI'; $request_url = $url . '/' . $collection_name;
Create a session for url:
$curl = curl_init($request_url);
We also have slightly changed the settings for the session:
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_HTTPHEADER, [ 'X-RapidAPI-Host: kvstore.p.rapidapi.com', 'X-RapidAPI-Key: 7xxxxxxxxxxxxxxxxxxxxxxx', 'Content-Type: application/json' ]);
As a result, we have the following file:
After its launch, we get the following response with information about the created collection:
3. Perform a PUT Request
Perform a PUT request to change data on the server. Suppose we want to set the public_write field to true. Implementing a PUT request combines the parameters we used to create GET and POST requests, with the difference in just a few parameters.
As a result, we get the following file:
true ]; $curl = curl_init($request_url); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'PUT'); curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data)); curl_setopt($curl, CURLOPT_HTTPHEADER, [ 'X-RapidAPI-Host: kvstore.p.rapidapi.com', 'X-RapidAPI-Key: 7xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', 'Content-Type: application/json' ]); $response = curl_exec($curl); curl_close($curl); echo $response . PHP_EOL;
- At the beginning of the given snippet, we form the URL as in the GET request example.
- Then we create an object in which we change the desired variable. Next, there are the settings almost as in the POST request example, only instead of CURLOPT_POST we use CURLOPT_CUSTOMREQUEST and give it the PUT value because we have a PUT request.
- We insert our prepared object in CURLOPT_POSTFIELDS in the necessary format, set headers, execute the request, and save results.
After running the created file, we get the response:
We can run GET snippet again and check:
Success! Data has changed.
4. The DELETE Method
It’s time to delete our collection using DELETE method. Deletion works the same as PUT, only we do not have the request body, and in the CURLOPT_CUSTOMREQUEST option, we insert the string DELETE. Having all this information, we get the following snippet:
And if we run it, we get the answer:
The server responds that the deletion was successful!
5. Repeat GET request and check if the data is really deleted
Everything is good. So we went through all the Request Methods.
How to Start Using an API with PHP / cURL
Now we know the basic elements of working with API in PHP, and we can create a step-by-step guide to creating a PHP app with API integration:
1. Get an API key
In order to start working with most APIs, you must identify yourself (register) and get an API key (a unique string of letters and numbers). You will need to add an API key to each request so that the API can recognize you. On the example of RapidAPI – you can choose the method of registration that will be convenient for you. This can be a username, email, and password: Google, Facebook, or Github account.
2. Test API Endpoints with PHP
After receiving the API key, we can make a request to API endpoints (according to the rules in the documentation) to check if everything works as we expected. In the case of working with RapidAPI, immediately after registering with the service, we can go to the section of the API of our interest, subscribe to it and test endpoints directly on the API page. Next, we can quickly create a PHP snippet using the cURL library with requests to the desired endpoint and test its work in the terminal.
3. Make your first PHP app with API
After checking endpoints, we can start creating an application, including the necessary API calls.
Simple PHP API Example
In this example, we will put together everything that we have learned and create our own news search engine using the Web Search API through RapidAPI. This API works under freemium conditions, allowing 10,000 free API requests per month. This will be more than enough for us.

1. Get an API key
After registering with RapidAPI service, we will receive a service key, and this will be enough for us to start work with the Web Search API. You can register by clicking on the ’Sign Up’ button on RapidAPI menu.

As mentioned earlier, you can register in any convenient way:

After registration, click Subscribe to Test button on Web Search API page and you can start using this API.

2. Test the API Endpoints
To create a news search engine we need newsSearch endpoint. We will specify the necessary parameters according to the documentation and look for the latest news about John Newman.

As we can see, API returns JSON with a selection of news about the singer. It seems that everything works as it should.
3. Make your first app with the API
Now we can start creating our news search engine. This will be an HTML page with a form and a button. The logic of work is simple: you enter a word, press a button, get a list of news about what you entered in the form.
First, let’s make a small HTML template with the form for sending a search request:
News Searcher
Now we need to write a php script that will process query field sent in the form and make an API request:
'true', 'pageNumber' => 1, 'pageSize' => 10, 'safeSearch' => 'false', 'q' => $_GET['query'] ]; $curl = curl_init($url . '?' . http_build_query($query_fields)); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_HTTPHEADER, [ 'X-RapidAPI-Host: contextualwebsearch-websearch-v1.p.rapidapi.com', 'X-RapidAPI-Key: 7xxxxxxxxxxxxxxxxxxxxxxxxxxxxx' ]); $response = json_decode(curl_exec($curl), true); curl_close($curl); $news = $response['value']; > ?>
Here are some explanations to the snippet above:
- _GET is an object (associative array) that contains variables passed to the script after the form is submitted. First, we check for the presence of query variable in the _GET array.
- After that, we enter the URL to which we will send the request, form an object (array) with the required parameters for the request (inclusively with the value of our query variable).
- Next comes the initialization of the cURL session with needed URL and a string with parameters from the query_fields object.
- Set the necessary parameters and headers.
- As a result, we execute the session and immediately translate the answer json_decode from the string into a PHP array.
- We close the session and save the news array to the $news variable.
We have received the $news variable with news, so all we have to do now is just to display them. To do this, we will add the following PHP snippet under our HTML form:
News by Your query:'; foreach ($news as $post) < echo '' . $post['title'] . '
'; echo 'Source'; echo 'Date Published: ' . $post['datePublished'] . '
'; echo '' . $post['body'] .'
'; echo '
'; > > ?>
This snippet is pretty simple.
In the beginning, we checked if our $news variable was empty. If $news is empty, then nothing is displayed, and if there is something in the $news variable, it will execute the entire code. We then loop through all the news in the array and use echo to display the required fields from each post.
We combine all our developments into one PHP file:
'true', 'pageNumber' => 1, 'pageSize' => 10, 'safeSearch' => 'false', 'q' => $_GET['query'] ]; $curl = curl_init($url . '?' . http_build_query($query_fields)); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_HTTPHEADER, [ 'X-RapidAPI-Host: contextualwebsearch-websearch-v1.p.rapidapi.com', 'X-RapidAPI-Key: 7xxxxxxxxxxxxxxxxxxxxxxxxxxx' ]); $response = json_decode(curl_exec($curl), true); curl_close($curl); $news = $response['value']; > ?>News Searcher
News by Your query:'; foreach ($news as $post) < echo '
' . $post['title'] . '
'; echo 'Source'; echo 'Date Published: ' . $post['datePublished'] . '
'; echo '' . $post['body'] .'
'; echo ''; > > ?>
To run our application, we need to write the code in the index.php file and then open a terminal in the folder with this file and execute the following command:
php -S localhost:5000
This command will start the test server. Our application will be available at https://localhost: 5000. Let’s take a look at it:

Let’s check out its work. Enter a topic on which we want to see the latest news into the form (in our case, this is “Area 51”):

Everything is working! We created our own news search engine. So far it is simple, but nothing will prevent us from gradually expanding its functionality.
Conclusion
In this article, we looked at the features and capabilities of the PHP/cURL bundle for working with API. We studied the implementation of Request Methods using PHP/cURL and even created our own news search service.
PHP is a simple and convenient language for quick web applications development, and by expanding its capabilities using APIs, you can create extremely powerful apps in a very short time.
Related Links
Related Tutorials
- How to use the Cricket Live Scores API (PHP)
- Yahoo Finance API (PHP)
- IMDb API in PHP
- Skyscanner Flight Search API (PHP)
- How to use the CoinMarketCap API
Related FAQ
How does an API Work?
API is an interface that allows your application to interact with an external service using a simple set of commands.
How do you use an API?
- Get an API Key
- Test API Endpoints
- Create your first App
What is an API used for?
APIs allow you to save time when developing and help not to invent a bicycle. It is much more efficient and more convenient to use the capabilities of one of the APIs than to try to independently implement similar functionality. Moreover, it will be problematic to get some functions and data other than through the API (for example, a weather forecast, a thematic selection of news, or a high-quality translation from almost any language).
Как правильно работать с REST API

![]()
15.05.2018
![]()
35368
Рейтинг: 5 . Проголосовало: 8
Вы проголосовали:
Для голосования нужно авторизироваться

Коротко обо мне
Меня зовут Зел, я разработчик-фрилансер из Сингапура. В свободное от работы время я люблю разбираться в коде и попутно публиковать в своем блоге те интересности, которые я обнаружил или изучил.
Вступление
Скорее всего вам уже приходилось слышать о таком термине, как REST API, особенно если вы сталкивались с необходимостью получения данных из другого источника (такого как Twitter или Github). Но что же все-таки это такое? Что мы можем с этим делать и как мы можем это использовать?
В данной статье вы узнаете все о REST API для того, чтобы работать с ними и читать связанную с ними документацию.
Что же такое REST API?
Давайте представим, что вы пытаетесь найти фильмы о Бэтмене на YouTube. Вы открываете сайт, вбиваете в форму поиска слово «Бэтмен», жмакаете «Окей» и видите список фильмов о супергерое. Похожим образом работает и WEB API. Вы ищите что-то и получаете список результатов от запрашиваемого ресурса.
Дословно API расшифровывается как Application Programming Interface. Это набор правил, позволяющий программам «общаться» друг с другом. Разработчик создает API на сервере и позволяет клиентам обращаться к нему.
REST – это архитектурный подход, определяющий, как API должны выглядеть. Читается как «Representational State Transfer». Этому набору правил и следует разработчик при создании своего приложения. Одно из этих правил гласит, что при обращении к определенному адресу, вы должны получать определенный набор данных (ресурс).

Каждый адрес маршрутом, пакет данных — запросом, в то время как результатирующий ресурс – ответом.
Анатомия запроса
Важно понимать структуру запроса:
- Маршрут отправки
- Тип метода
- Заголовки
- Тело (или данные)
Маршрут – это адрес, по которому отправляется ваш запрос. Его структура примерно следующая:

Root-endpoint — это точка приема запроса на стороне сервера (API). К примеру, конечная точка GitHub – https://api.github.com.
Путь определяет запрашиваемый ресурс. Это что-то вроде автоответчика, который просит вас нажать 1 для одного сервиса, 2 для другого и так далее.
Для понимания того, какие именно пути вам доступны, вам следует просмотреть документацию. К примеру, предположим, вы хотите получить список репозиториев для конкретного пользователя на Git. Согласно документации, вы можете использовать следующий путь для этого:

Вам следует подставить под пропуск имя пользователя. К примеру, чтобы найти список моих репозиториев, вы можете использовать маршрут:

Последняя часть маршрута – это параметры запроса. Технически запросы не являются частью REST-архитектуры, но на практике сейчас все строится на них. Так что давайте поговорим о них более детально. Параметры запроса позволяют использовать в запросе наборы пар «ключ-значение». Они всегда начинаются знаком вопроса. Каждая пара параметров после чего разделяется амперсантом (что-то вроде этого):

Как только вы пытаетесь получить список репозиториев для пользователя, вы добавляете эти три опциональных параметра и после чего получаете следующий результат:
Тема связана со специальностями:

Если же вы желаете получить список моих недавно запушеных репозиториев, вам следует ввести следующее:

Итак, как же понять, что маршруты рабочие? Что ж, пришло время проверить их на практике!
Тестирование при помощи Curl
Вы моете отправить запрос при помощи любого языка программирования. JavaScript может использовать методы вроде Fetch API или JQuery`s Ajax Method. Руби использует другое. И так далее.
В этой статье я буду использовать такую утилитку, как Curl. Дело в том, что она указана в официальной документации для веб-сервисов. Если вы поймете, как использовать эту утилиту, вы поймете, как работать с API. После чего вы можете производить запросы любым удобным для вас языком.
Перед тем, как продолжить, вам следует убедится, что Curl установлен на вашей машине.

Ели же он не установлен, самое время установить. В таком случае вы получите ошибку «command not found».
Для того, чтобы использовать утилиту, необходимо ввести следующее (по примеру):

И как только вы подтверждаете ввод, вы получаете ответ (наподобие этого):

Чтобы получить список пользовательских репозиториев, вам следует изменить запрос по тому же принципу, который был оговорен ранее. К примеру, чтобы получить список моих репозиториев, вам следует ввести следующее:

Если же вы желаете включить параметры запросов, убедитесь, что вы их экранируете. Дело в том, что без экранирования знаки вопроса и равно расцениваются системой как спец. символы и выполнение команды произойдет с ошибкой.

Также попробуйте другие команды и произведите запросы! В результате вы получаете похожие ответы.
JSON
JSON – JavaScript Object Notation – общий формат для отправки и приема данных посредством REST API. Ответ, отправляемый Github, также содержится в формате JSON.

Возвращаемся к анатомии запроса
Вы изучили, что запрос состоит из четырех частей:
- Маршрут отправки
- Тип метода
- Заголовки
- Тело (или данные)
Теперь же давайте попробуем разобраться с остальным.
Тип метода
Метод обозначает тип производимого запроса, де-факто он является спецификацией операции, которую должен произвести сервер. Всего существует пять типов запросов:
GET – используется для получения со стороны севера определенного ресурса. Если вы производите этот запрос, сервер ищет информацию и отправляет ее вам назад. По сути, он производит операцию чтения на сервере. Дефолтный тип запросов.
POST – нужен для создания определенного ресурса на сервере. Сервер создает в базе данных новую сущность и оповещает вас, был ли процесс создания успешным. По сути, это операция создания.
PUT и PATCH – используются для обновления определенной информации на сервере. В таком случае сервер просто изменяет информацию существующих сущностей в базе данных и оповещает об успехе выполнения операции.
DELETE – как и следует из названия, удаляет указанную сущность из базы или сигнализирует об ошибке, если такой сущности в базе не было.
Сам же API позволяет указать, какой метод должен быть использован в определенных контекстных ситуациях.

GET запрос в этом случае необходим, чтобы получить список всех репозиториев указанного пользователя. Также можно использовать curl:

Попробуйте отправить этот запрос. В качестве ответа вы получите требование об аутентификации.

Заголовки
Заголовки используются, чтобы предоставить информацию как клиенту, так и серверу. Вообще, их можно использовать для много чего – пример – та же самая аутентификация и авторизация. Найти список доступных заголовком можно на официальной странице MDN.
Видео курсы по схожей тематике:

Введение в Entity Framework. Шаблоны разработки Entity Framework

Unity Стартовый 2015

Практический курс по верстке лендинга
Заголовки представляют из себя пары ключей-значений. Пример:

Также пример с использованием curl:

(Примечание: заголовок Content-Type в случае Github для работы не является обязательным. Это всего лишь пример использования заголовка в запросе, ничего более.)
Для просмотра отправленных заголовком можно использовать следующее:


Здесь звездочка относится к дополнительной информации, предоставленной посредством curl. > относится к заголовкам запроса, а
Чтобы отправить информацию с curl, используйте следующее:

Для отправки множественных полей, мы можем использовать несколько подобных конструкций:

Также, если необходимо, вы можете разбить ваш запрос на несколько линий для обеспечения большей читабельности:

Если вы знаете, как развернуть сервер, вы можете создать собственный API и протестировать свои запросы. Если же нет, обязательно попробуйте. Существует множество информации, посвященной этому.
Если же желания разворачивать свой сервер нет, попробуйте бесплатную опцию Request bin.

После чего вы получите адрес, который спокойно сможете тестировать.

Убедитесь, что вы создаете свой собственный request bin, если вы хотите протестировать именно ваш запрос. Учитывайте, что дефолтное время существования request bin – 48 часов. Потому те примеры адресов, которые я здесь привожу, на момент прочтения статьи давно как устарели.
Теперь же попробуйте отправить некоторую информацию, после чего обновите свою страницу.
Если все пройдет успешно, вы увидите следующее:


По умолчанию curl отправляет данные так, как если бы они были отправлены посредством полей форм. Если вы хотите отправить данные через JSON, ваш Content-Type должен равняться application\json, впоследствии вам необходимо отформатировать данные в виде JSON-объекта.


По сути, это все, что вам необходимо знать о структуре запроса.
Теперь давайте вспомним об аутентификации. Что же это такое и для чего она нужна?
Аутентификация
Вы бы не позволили никому чужому получить доступ к вашему банковскому счету без специального разрешения, не так ли? По такому же принципу разработчики не позволяют неавторизированным пользователям производить на сервере все, что им вздумается.
Так как POST, PUT, PATCH, DELETE запросы изменяют базу данных, разработчики должны всегда быть на страже неавторизированного доступа к ним. Впрочем иногда GET запросы также требуют аутентификации (к примеру, когда вы желаете посмотреть состояние вашего банковского счета).
В случае с вебом существует два способа представиться системе:
- Через ник и пароль (базовая аутентификация)
- Через секретный токен
Секретный токен позволяет представить вас системе через соц. Сети по типу Github, Google, Twitter и так далее.
Здесь же я рассмотрю только базовую аутентификацию.
Для произведения базовой аутентификации вы можете использовать следующее:

Попробуйте залогиниться под свой профиль по запросу, указанному выше. Как только вы успешно войдете в свой профиль, вы увидите ответ «problems parsing JSON».
Почему? Все просто: системе-то вы представились, но – вот беда – ничего полезного ей не предоставили. Все типы запросов требуют определенной информации.
Теперь же давайте поговорим о статус-кодах и возможных ошибках.
Статус-коды и возможные ошибки
Некоторые из сообщений, приведенных выше, как раз-таки и относятся к кодам ошибок. Логично, что они появляются только, когда что-то идет не совсем так, как было запланировано. Что же касательно статуса кодов, они позволяют вам познать успех (или неудачу) при выполнении определенного запроса. Бывают статус-коды от 100 до 500+. В целом их можно разделить на следующие группы:
- 200+: запрос успешен
- 300+: запрос перенаправлен на другой маршрут
- 400+: ошибка на стороне клиента
- 500+: ошибка на стороне сервера
Вы можете отладить статус ответа при помощи –v или –verbose. К примеру, я попытался получить доступ к определенному ресурсу без авторизации. Следовательно, я поймал ошибку:

В случае же, когда запрос не верен по причине ошибки в самой передаваемой информации, вы получаете статус-код 400:

Версии API
Время от времени разработчики обновляют свои API. Порой обновления могут быть такими сильными, что разработчик желает выпустить релиз новой версии. В таком случае, если ваше приложение ломается, это происходит по причине, что вы писали код с учетом старого компонента, тогда как новый несколько отличается в плане реализации.
Бесплатные вебинары по схожей тематике:

Интерактивный вебинар. Soft Skills на интервью и на испытательном сроке

Как разработчику найти первую работу в IT

Какие алгоритмы должен знать программист
Запросить текущую версию API можно двумя путями.
- Через маршурт
- Через заголовок
К примеру, Твиттер использует первый метод. На момент написания версия Твиттер API была 1.1.

С другой стороны, GitHub использует другой способ:

В заключение
В этой статье мы рассмотрели, что такое REST API и как его можно использовать совместно с curl. Кроме того, вы также выучили, как залогиниться при помощи запроса и что такое статус-код.
Я искренне надеюсь, что эта статья позволила вам повысить свой уровень общих и не очень познаний касательно такого немаловажного аспекта веб-разработки. Буду рад любым вашим комментариям здесь.
Автор перевода: Евгений Лукашук
Еще больше материалов по данной теме:
Введение в Google Analytics API: краткое руководство по PHP для веб-приложений
Оптимизируйте свои подборки Сохраняйте и классифицируйте контент в соответствии со своими настройками.
В этом руководстве описывается, как получить доступ к аккаунту Google Analytics, отправлять запросы в API этого сервиса, обрабатывать ответы и извлекать результаты обработки с применением Core Reporting API 3.0, Management API 3.0 и OAuth 2.0.
Примечание. Цель этих кратких руководств – помочь пользователю выполнить авторизацию API с помощью клиентских библиотек Google API. Поскольку эти библиотеки постоянно обновляются, информации о последних изменениях здесь может не быть. Если вы не нашли нужные сведения, ознакомьтесь с документацией по клиентским библиотекам и справочной информацией.
Шаг 1. Включите Google Analytics API
Перед началом работы с Google Analytics API используйте инструмент настройки, чтобы создать проект в Google API Console, включить API и зарегистрировать учетные данные.
Чтобы создать идентификатор веб-клиента или клиента установленного приложения, нужно указать название продукта в окне запроса доступа. Если вы ещё не указали название, вам будет предложено это сделать.
Создайте идентификатор клиента
Откройте раздел «Учетные данные» и выполните следующие действия:
- Нажмите Создать учетные данные и выберите вариант Идентификатор клиента OAuth.
- В разделе Тип приложения выберите Веб-приложение.
- Введите название.
- Поле Разрешенные источники JavaScript оставьте пустым.
- В поле Разрешенные URI перенаправления введите http://localhost:8080/oauth2callback.php.
- Нажмите кнопку Создать.
Выберите созданные учетные данные и нажмите Скачать файл JSON. Сохраните файл как client_secrets.json . Он понадобится вам позже.
Шаг 2. Установите клиентскую библиотеку Google
composer require google/apiclient:^2.0
Шаг 3. Настройте пример
Создайте два файла:
- index.php – для главной страницы, которую посещает пользователь.
- oauth2callback.php – для обработки OAuth 2.0 response.
index.php
Этот файл содержит основной код для запросов Google Analytics API и отображения результатов. Скопируйте или скачайте пример кода для index.php .
setAuthConfig(__DIR__ . '/client_secrets.json'); $client->addScope(Google_Service_Analytics::ANALYTICS_READONLY); // If the user has already authorized this app then get an access token // else redirect to ask the user to authorize access to Google Analytics. if (isset($_SESSION['access_token']) && $_SESSION['access_token']) < // Set the access token on the client. $client->setAccessToken($_SESSION['access_token']); // Create an authorized analytics service object. $analytics = new Google_Service_Analytics($client); // Get the first view (profile) id for the authorized user. $profile = getFirstProfileId($analytics); // Get the results from the Core Reporting API and print the results. $results = getResults($analytics, $profile); printResults($results); > else < $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/oauth2callback.php'; header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL)); >function getFirstProfileId($analytics) < // Get the user's first view (profile) ID. // Get the list of accounts for the authorized user. $accounts = $analytics->management_accounts->listManagementAccounts(); if (count($accounts->getItems()) > 0) < $items = $accounts->getItems(); $firstAccountId = $items[0]->getId(); // Get the list of properties for the authorized user. $properties = $analytics->management_webproperties ->listManagementWebproperties($firstAccountId); if (count($properties->getItems()) > 0) < $items = $properties->getItems(); $firstPropertyId = $items[0]->getId(); // Get the list of views (profiles) for the authorized user. $profiles = $analytics->management_profiles ->listManagementProfiles($firstAccountId, $firstPropertyId); if (count($profiles->getItems()) > 0) < $items = $profiles->getItems(); // Return the first view (profile) ID. return $items[0]->getId(); > else < throw new Exception('No views (profiles) found for this user.'); >> else < throw new Exception('No properties found for this user.'); >> else < throw new Exception('No accounts found for this user.'); >> function getResults($analytics, $profileId) < // Calls the Core Reporting API and queries for the number of sessions // for the last seven days. return $analytics->data_ga->get( 'ga:' . $profileId, '7daysAgo', 'today', 'ga:sessions'); > function printResults($results) < // Parses the response from the Core Reporting API and prints // the profile name and total sessions. if (count($results->getRows()) > 0) < // Get the profile name. $profileName = $results->getProfileInfo()->getProfileName(); // Get the entry for the first entry in the first row. $rows = $results->getRows(); $sessions = $rows[0][0]; // Print the results. print "First view (profile) found: $profileName
"; print "Total sessions: $sessions
"; > else < print "No results found.
"; > > ?>
oauth2callback.php
Этот файл обрабатывает ответ OAuth 2.0. Скопируйте или скачайте пример кода для oauth2callback.php .
setAuthConfig(__DIR__ . '/client_secrets.json'); $client->setRedirectUri('http://' . $_SERVER['HTTP_HOST'] . '/oauth2callback.php'); $client->addScope(Google_Service_Analytics::ANALYTICS_READONLY); // Handle authorization flow from the server. if (! isset($_GET['code'])) < $auth_url = $client->createAuthUrl(); header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL)); > else < $client->authenticate($_GET['code']); $_SESSION['access_token'] = $client->getAccessToken(); $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/'; header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL)); >
Шаг 4. Запустите пример
После того как вы включите Google Analytics API, установите клиентскую библиотеку Google API для PHP и настроите код примера, он будет готов к запуску.
Запустите образец на веб-сервере, который поддерживает PHP. Если вы используете PHP 5.4 или более позднюю версию, вам доступен встроенный тестовый веб-сервер. Просто введите команду:
php -S localhost:8080 /path/to/sample
Затем перейдите на страницу http://localhost:8080 в браузере.
После выполнения всех шагов будет выведено название первого профиля авторизованного пользователя в Google Analytics и количество сеансов за последние семь дней.
Примечание. Для успешного запуска примера нужно иметь по крайней мере один ресурс и профиль Google Analytics.
Имея авторизованный служебный объект Analytics, вы можете запустить любой из примеров кода, приведенных в справочных материалах по Management API. Например, можно попробовать изменить код, чтобы использовать метод accountSummaries.list.
Если не указано иное, контент на этой странице предоставляется по лицензии Creative Commons «С указанием авторства 4.0», а примеры кода – по лицензии Apache 2.0. Подробнее об этом написано в правилах сайта. Java – это зарегистрированный товарный знак корпорации Oracle и ее аффилированных лиц.
Последнее обновление: 2019-01-23 UTC.