Google Sheet/구글 시트 API 레퍼런스, 소스 읽는 법_ PHP 버전
퀵스타터 예제를 실행해보고, 본격적으로 구글 시트 API 레퍼런스를 읽어보자.
레퍼런스를 읽으면서 GitHub 에 있는 소스도 따라가느라 복잡하게 느껴질 수 있지만 그래도 해봅시다!
언어설정에서 한국어 로 설정할 수도 있지만, 메뉴만 한글로 되어있고 내용은 영어 그대로이다.
https://developers.google.com/sheets/api/reference/rest/
공식 홈페이지에 올라온 레퍼런스는 REST API 이다.
PHP로 개발하려고 했는데 REST 뿐인가!
GitHub 에 올려진 구글API PHP 클라이언트 소스 읽는 법을 정리해본다.
구글 API PHP 클라이언트로 구글 시트 뿐만 아니라 구글에서 제공하는 거의 대부분의 서비스를 이용할 수 있다.
살펴봐야할 메인 폴더는 src/Google/Service
A로 시작하는 서비스만 해도 이~~렇게나 많다.
폴더들을 지나쳐 아래로 쭉쭉 내려가 보면 Sheets.php 라는 구글 시트 관련된 클래스파일이 있다.
$service = new Google_Service_Sheets($client);
구글 시트 PHP 클라이언트 호출할 때 Google_Service_Sheets 클래스를 이용하는데, 바로 그 파일이 Sheets.php
클래스 파일을 보면 어떻게 활용할 수 있는지 알 수 있다.
/**
* Constructs the internal representation of the Sheets service.
*
* @param Google_Client $client
*/
public function __construct(Google_Client $client)
{
parent::__construct($client);
클래스 객체 생성할 때 가장 기본이 되는 생성자 부분
Google_Client 를 인자로 넣어주도록 되어있다.
$client 는 퀵스타터 예제에 있는 클라이언트 객체 생성부분을 참고하면 되겠다.
구글 시트 API 문서를 보면 4개의 REST 리소스 항목이 나오는데, 클래스에서 퍼블릭 변수와 각각 대응을 한다.
새로운 구글 스프레드시트 생성하는 예제코드를 본다.
$client = getClient();
$service = new Google_Service_Sheets($client);
// TODO: Assign values to desired properties of `requestBody`:
$requestBody = new Google_Service_Sheets_Spreadsheet();
$response = $service->spreadsheets->create($requestBody);
스프레드시트 생성은 $service->spreadsheets->create($requestBody); 이 부분에서 작업이 된다.
Google_Service_Sheets 객체($service)에서 화살표(->)로 spreadsheets 를 호출하니까
spreadsheets 가 멤버변수인 걸 알 수 있다. 위에 캡처이미지에서도 멤버변수인 것 확인~
$this->spreadsheets = new Google_Service_Sheets_Resource_Spreadsheets(
$this,
$this->serviceName,
'spreadsheets',
array(
'methods' => array(
'batchUpdate' => array(
'path' => 'v4/spreadsheets/{spreadsheetId}:batchUpdate',
'httpMethod' => 'POST',
'parameters' => array(
'spreadsheetId' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
),
),'create' => array(
'path' => 'v4/spreadsheets',
'httpMethod' => 'POST',
'parameters' => array(),
)
spreadsheets 변수에 할당된 객체를 보니 Google_Service_Sheets_Resource_Spreadsheets 클래스이다.
해당 클래스를 찾아가기 위해서는 Sheets 폴더로 들어간다.
온갖 구글 스프레드시트 관련된 클래스가 모여있다. 파일이름만 봐도 어떤 클래스인지 알 수 있다.
여기서 주의할 점은 클래스명과 파일명은 같지 않다는 것이다.
즉, 발견한 클래스명 으로 F3 눌러서 검색해봤자 아무것도 안 나온다.
클래스명에서 파일명을 유추해야 한다.
Google_Service_Sheets_Resource_Spreadsheets 에서 Resource 폴더에 들어있을 것 같다.
여기까지 왔으니 이 중에서 Spreadsheets.php 가 아닐까?
class Google_Service_Sheets_Resource_Spreadsheets extends Google_Service_Resource
찾았다! Google_Service_Sheets_Resource_Spreadsheets 클래스
public function create(Google_Service_Sheets_Spreadsheet $postBody, $optParams = array())
{
$params = array('postBody' => $postBody);
$params = array_merge($params, $optParams);
return $this->call('create', array($params), "Google_Service_Sheets_Spreadsheet");
}
멤버함수인 create 를 보면 인자로 Google_Service_Sheets_Spreadsheet 객체를 필요로 한다.
잠깐 Google_Service_Sheets_Spreadsheet 클래스의 내용을 살펴보면,
자바 스프링의 DTO(Data Transfor Object) 객체같은 역할을 하는지 멤버변수에 대해 getter 와 setter 함수로 접근하게 되어있다.
그러기 때문에 이 객체를 $requestBody 로 생성하여 create 에 인자로 넘겨주는 것이다.
이대로 간단하게 끝나면 좋겠지만, 레퍼런스 문서의 예제에 빠진 부분이 있다.
Assign values to desired properties of `requestBody` //`requestBody`의 원하는 속성에 값을 할당하십시오.
당황하지 말고 구글에서 제공한 테스트 폼을 먼저 이용해 본다. Try this API 영역 이용하기!
Request body 영역에 아무 파라미터 값을 안 줘도 파일 생성은 잘 된다.
여기서 확인해보는 것은 properties 항목이다.
가장 기본이 되는 스프레드시트 파일명을 지정해야 하는데 Google_Service_Sheets_Spreadsheet 의 setter 함수 중에서 힌트를 찾을 수 있었다.
/**
* @param Google_Service_Sheets_SpreadsheetProperties
*/
public function setProperties(Google_Service_Sheets_SpreadsheetProperties $properties)
{
$this->properties = $properties;
}
Google_Service_Sheets_SpreadsheetProperties 클래스 이용하기
class Google_Service_Sheets_SpreadsheetProperties extends Google_Model
{
public $autoRecalc;
protected $defaultFormatType = 'Google_Service_Sheets_CellFormat';
protected $defaultFormatDataType = '';
protected $iterativeCalculationSettingsType = 'Google_Service_Sheets_IterativeCalculationSettings';
protected $iterativeCalculationSettingsDataType = '';
public $locale;
public $timeZone;
public $title;
properties 의 항목들이 클래스의 멤버변수들로 들어있고,
셀 포맷 설정은 한 번 더 타고 들어가서 어떤 항목들이 있는지 확인할 수 있다.
구글 시트 API 가이드문서에는 Using the Sheets API 가 있어서 간단한 사용법이 나와있다.
실제로 PHP 소스로 입력해본다.
<?php
require __DIR__ . '/../vendor/autoload.php';
if (php_sapi_name() != 'cli') {
throw new Exception('This application must be run on the command line.');
}
/**
* Returns an authorized API client.
* @return Google_Client the authorized client object
*/
function getClient()
{
$client = new Google_Client();
$client->setApplicationName('Google Sheets API PHP Quickstart');
$client->setScopes(Google_Service_Sheets::SPREADSHEETS_READONLY);
$client->setAuthConfig('../credentials.json');
$client->setAccessType('offline');
$client->setPrompt('select_account consent');
// Load previously authorized token from a file, if it exists.
// The file token.json stores the user's access and refresh tokens, and is
// created automatically when the authorization flow completes for the first
// time.
$tokenPath = 'token.json';
if (file_exists($tokenPath)) {
$accessToken = json_decode(file_get_contents($tokenPath), true);
$client->setAccessToken($accessToken);
}
// If there is no previous token or it's expired.
if ($client->isAccessTokenExpired()) {
// Refresh the token if possible, else fetch a new one.
if ($client->getRefreshToken()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
} else {
// Request authorization from the user.
$authUrl = $client->createAuthUrl();
printf("Open the following link in your browser:\n%s\n", $authUrl);
print 'Enter verification code: ';
$authCode = trim(fgets(STDIN));
// Exchange authorization code for an access token.
$accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
$client->setAccessToken($accessToken);
// Check to see if there was an error.
if (array_key_exists('error', $accessToken)) {
throw new Exception(join(', ', $accessToken));
}
}
// Save the token to a file.
if (!file_exists(dirname($tokenPath))) {
mkdir(dirname($tokenPath), 0700, true);
}
file_put_contents($tokenPath, json_encode($client->getAccessToken()));
}
return $client;
}
// Get the API client and construct the service object.
$client = getClient();
$service = new Google_Service_Sheets($client);
// TODO: Assign values to desired properties of `requestBody`:
$requestBody = new Google_Service_Sheets_Spreadsheet([
'properties' => [
'title' => $title
]
]);
$response = $service->spreadsheets->create($requestBody, [
'fields' => 'spreadsheetId'
]);
printf("Spreadsheet ID: %s\n", $spreadsheet->spreadsheetId);
// TODO: Change code below to process the `response` object:
echo '<pre>', var_export($response, true), '</pre>', "\n";
?>
이전 글에서 quickstart.php 파일이 위치한 곳에 createSheet.php 파일을 생성한다.
cmd 창에서 실행하기
스프레드시트 아이디와 파일생성 결과가 출력되어야 하는데...
레퍼런스 페이지에서 테스트 했을 때와는 다르게 권한에러가 난다.
권한부여요청에 대해서 추가작업이 필요하다.