Jump to content
과거의 기술자료(읽기 전용): https://tech.devgear.co.kr ×
과거의 기술자료(읽기 전용): https://tech.devgear.co.kr

WeatherStack을 활용한 델파이 데모 (APILayer 사용)


Recommended Posts

 

I recently gave a presentation about the use of cloud and REST APIs from Delphi at the Italian Delphi Day conference, at the end of June. Among the various demos, I made some experiments using APILayer REST APIs. In case you don’t know, APILayer is a company that is part of Idera, like Embarcadero.

지난 6월 이탈리아 델파이 데이 컨퍼런스에서 델파이에서 클라우드와 REST API 활용 방안을 주제로 발표를 했었다. 다양한 데모 중에서도 APILayer REST API를 활용한 예제들을 소개했었는데, 그에 대한 내용을 정리하려고 한다. 아는 분도 계시겠지만, APILayer는 엠바카데로처럼 아이데라 사의 회사 중 하나이다.

 

목차


 

왜 REST API인가

Before we explore specific APIs and demos, I’d like to discuss the relevance of using APIs in the context of a client application like those built with Delphi. In the past, the most common way to add a feature to a program was to write the proper code or use an existing library to add the capability, and distribute the compiled code of the feature along with the application.

특정 API와 데모를 살펴보기 전에, 델파이로 개발한 프로그램들처럼 클라이언트 애플리케이션에서의 API 활용 관련하여 이야기해보고자 한다. 과거에는 프로그램에 기능을 추가하는 가장 일반적인 방법은 적당한 코드를 작성하고 기존 라이브러리를 사용하는 것이었다. 애플리케이션과 컴파일된 기능 코드를 같이 배포하는 것이다.

 

Today’s online services and REST APIs often offer similar capabilities activated by passing proper parameters with an HTTP call to a server and receiving back the result. Examples include image transformations, creating a PDF, transforming text to speech or reading the text embedded in an image.

요즘의 온라인 서비스와 REST API는 HTTP 호출을 통해 적합한 파라메터를 서버에 전달하고 그 결과를 다시 수신해 활성화한 기능들을 제공하곤 한다. 이미지 변환, PDF 생성, 텍스트 음성 변환이나 이미지에 포함된 텍스트 읽기 등이 이러한 예이다.

 

Why would you use one approach over the other? There are cases in which only one of the alternatives is realistic (fast performance graphic rendering requires an installed graphic library while an AI capability is generally available online), but in other scenarios both approaches might be possible.

다른 방법 보다 한 가지 접근 방식을 사용하는 이유는 무엇일까? 대안 중 하나의 방법만이 현실적인 경우도 있겠지만 (신속한 성능 그래픽 렌더링은 그래픽 라이브러리 설치가 필요한 반면, AI 기능은 보통 온라인에서 사용 가능), 또 다른 경우에서는 두 가지 접근 방식 모두 가능할 수도 있다.

 

로컬 라이브러리 사용에는 다음과 같은 이점이 있다:

  • 보통 실행이 더 빠르다.
  • 인터넷 연결이 필요없다.
  • 코드 및 UI와 더 잘 결합할 수 있는 기능을 미세하게 조정하거나 커스터마이징 할 수 있다.
  • 보안 측면에서는 전송 중인 애플리케이션 데이터에 누군가 접속하는 것을 방지하기 위한 통신 암호화를 걱정할 필요가 없다.

 

REST API 사용에는 다음과 같은 이점이 있다:

  • 추가 라이브러리 코드를 배포할 필요가 없어, 앱을 더 작게 유지할 수 있다.
  • 클라이언트 애플리케이션과 별도로 업데이트할 수 있어, 항상 최신 버전의 라이브러리를 사용할 수 있다.
  • 보안 측면에서 문제 발견 시 라이브러리 업데이트, 새 버전 애플리케이션 배포에 대한 걱정을 할 필요가 없다.

 

마지막으로, 라이브러리 vs. REST API 비용 차이가 있다:

  • 라이브러리가 무료이고 오픈 소스인 경우가 아니라면, 일반적으로 개발자 당 선불 고정 비용이 발생한다.
  • 대부분의 REST API는 사용량 당 지불(Pay per use) 모델이 있고, 개발이나 테스트에 사용할 수 있는 무료 버전도 있다.
  • 따라서 REST API는 제한된 용도로 사용할 경우 비용을 더 줄일수도 있지만, 사용 범위가 넓은 경우 비용이 더 많이 들 수도 있다.

 

APILayer 소개

APILayer is an Idera business focused on offering hosted APIs and on creating an API Marketplace, hosting also third-party APIs. You can read more about the many available services at https://apilayer.com/

APILayer는 아이데라 비즈니스 중 하나로, 호스팅된 API를 제공하고 API 마켓플레이스 구성에 중점을 두고 있으며, 써드파티 API도 호스팅한다. 이용 가능한 서비스에 대한 더 많은 정보는 https://apilayer.com/ 에서 확인할 수 있다.

 

There are many powerful APIs as part of APILayer, and while some make more sense in a web application (like IpStack), many others make perfect sense also in a client application, like the file processing services offered by FileStack (https://www.filestack.com/) or the nifty third-party email verification Api (https://apilayer.com/marketplace/email_verification-api).

APILayer에는 강력한 API가 많이 있으며, 웹 애플리케이션 (IpStack 등)에 적합한 API도 있고, 훌륭한 써드파티 이메일 인증 API(https://apilayer.com/marketplace/email_verification-api) 및 FileStack(https://www.filestack.com/)에서 제공하는 파일 프로세싱 서비스처럼 클라이언트 애플리케이션에 가장 적합한 것도 있다.

 

In my demo below I’ll focus on a simple API, possibly not the most powerful one: WeatherStack, which as the name implies can deliver current, historical and forecast data about the weather: https://weatherstack.com/

이번 데모에서는 가장 강력한 API가 아닌 간단한 API에 초점을 맞추어보겠다. 이름에서도 알 수 있듯 WeatherStack은 날씨 관련 최신, 과거, 예측 데이터를 제공한다. https://weatherstack.com/

 

RAD스튜디오 REST Debugger 활용

Once you have identified the REST API you plan to use, the easiest way to start developing a client application is to use the REST Debugger, available as part of RAD Studio installation (and accessible from the Tools menu) and also as a separate free download for anyone (https://www.embarcadero.com/free-tools/rest-debugger).

사용하고자 하는 REST API를 확인했다면, 클라이언트 애플리케이션 개발 시작의 가장 쉬운 방법은 REST Debugger를 사용하는 것이다. 이는 RAD스튜디오 설치 중 있는 것으로 (Tools 메뉴에서도 선택 가능), 누구나 무료 다운로드 페이지에서 받을 수도 있다 (https://www.embarcadero.com/free-tools/rest-debugger).

 

The debugger offers the ability to configure a REST API, save that configuration for future use (or to share it with another developer), and import the configuration in a Delphi or C++Builder application.

디버거는 REST API를 구성할 수 있고, 나중에 사용할 수 있도록 (또는 다른 개발자와 공유할 수 있도록) 구성 저장도 가능하고, 델파이나 C++빌더 애플리케이션에 구성을 임포트할 수도 있다.

 

In a simple case, like that of WeatherStack, after you start the REST Debugger you first have to configure the primary endpoint:

WeatherStack의 경우, REST Debugger를 먼저 실행한 후 프라이머리 엔드포인트를 먼저 구성해야 한다:

spacer.png

 

Next you need to set the proper parameters configuration, including the specific endpoint (current), the query parameter and the access_key authentication information:

그런 다음 알맞은 파라메터 구성을 설정한다. 파라메터 구성에는 특정 엔드포인트 (기존), 쿼리 파라메터, access_key 인증 정보가 포함되어 있어야 한다:

spacer.png

 

The parameters depend on the endpoint and are listed in the API documentation. At this point you can use the SendRequest button to try the API and check the response in the bottom portion of the REST Debugger UI:

파라메터는 엔드포인트에 따라 달라지며, API 설명서에도 나와 있다. 여기에서 SendRequest 버튼을 사용해 API를 넣어보고, REST Debugger UI 하단 부분에서 응답을 확인할 수 있다:

spacer.png

 

The resulting data structure is relatively complex, but we can filter out some of the nested tables (like location visible above) in a table structure. Given we are likely looking for the current data, we can use that JSON root element to get the data in a table structure:

결과 데이터 구조는 복잡하긴 하지만, 테이블 구조의 중첩 테이블 (위에서 볼 수 있는 위치 처럼)을 필터링할 수 있다. 현재 데이터를 찾고 있다면, JSON 루트 요소를 사용해 테이블 구조에서 데이터를 가져올 수도 있다:

spacer.png

 

델파이에서 실제 데모 구축하기

Once you are happy with the configuration and the data A(possibly including the table data) you can use the Copy Component button of the REST Debugger to streamline the development of an application. This button, in fact, captures the REST Client Library components configuration and allows you to  paste it into a form or data module in the RAD Studio IDE.

설정과 데이터 A (테이블 데이터 포함)에 만족한다면, REST Debugger의 Copy Component 버튼을 클릭해 애플리케이션 개발을 간소화 할 수 있다. 사실상 이 버튼은 REST Client Library 컴포넌트 구성을 캡쳐하여 RAD스튜디오 IDE의 폼이나 데이터 모듈에 붙여넣을 수 있다.

 

In this case I just created a simple FireMonkey application with Delphi, added a data module, and pasted the components configuration in it. It results in the following data module:

여기에 데이터 모듈을 추가하고 컴포넌트 구성을 붙여넣어서 델파이로 간단한 파이어몽키 애플리케이션을 만들어보았다. 다음과 같이 데이터 모듈이 생성된다:

spacer.png

 

The actual configuration of the components is the following:

컴포넌트 실제 구성은 다음과 같다:

object DataModule14: TDataModule14
  object RESTClient1: TRESTClient
    BaseURL = 'http://api.weatherstack.com'
  end
  object RESTRequest1: TRESTRequest
    Client = RESTClient1
    Params = <
      item
        Name = 'access_key'
        Value = 'xxxxxxxxxxxxxxxxx'
      end
      item
        Name = 'query'
        Value = 'Piacenza, Italy'
      end>
    Resource = 'current'
    Response = RESTResponse1
  end
  object RESTResponse1: TRESTResponse
    RootElement = 'current'
  end
  object RESTResponseDataSetAdapter1: TRESTResponseDataSetAdapter
    Dataset = FDMemTable1
    Response = RESTResponse1
    TypesMode = JSONOnly
  end
  object FDMemTable1: TFDMemTable
    FetchOptions.AssignedValues = [evMode]
    FetchOptions.Mode = fmAll
  end
end

 

As you the see, the RESTClient component has the overall configuration of the site, the RESTRequest refers to the endpoint and its parameters, the optional RESTResponse component holds the results and can pass it via the RESTResponseDataSetAdapter component to an in-memory table, the FDMemTable component.

확인할 수 있듯, RESTClient 컴포넌트에는 사이트의 전반적인 구성이 있으며, RESTRequest는 엔드포인트와 그 파라메터를 참조한다. 옵션으로 선택하는 RESTResponse 컴포넌트는 결과를 보관하고 RESTResponseDataSetAdapter 컴포넌트를 통해 인메모리 테이블인 RDMemTable 컴포넌트에 결과를 전달하게 된다.

 

At this point, what you need in the main form is a button to make the call and an edit box with the location and a display component (I’ve used a read only edit box). In the button’s OnClick event handler, you can write some code like the following:

이 때, 메인 폼에는 호출할 수 있는 버튼 그리고 위치와 정보를 표시해 줄 에디트 박스가 두 개 필요하다 (나는 읽기 전용 에디트 박스를 사용했다). 버튼 OnClick 이벤트 핸들러에는 다음의 코드를 작성한다:

procedure TForm13.BtnRefreshClick(Sender: TObject);
begin
  DataModule14.RESTRequest1.Params[1].Value := EditLocation.Text;
  DataModule14.RESTRequest1.Execute();
  EditCurrent.Text := DataModule14.FDMemTable1.FieldByName('temperature').AsString;
end;

As an alternative, you can tie the input and the out via Visual LiveBindings, connecting the input edit to the request parameters and the specific field of the in-memory table to the output control.To be able to do this, you first have to execute the HTTP request at design time, using a specific command of the RESTRequest component. This populates components metadata, including the in-memory table. After doing it, you can wire the input and the output in the LiveBindings designer, and reside the code executed when pressing the button to:

또는 비주얼 라이브바인딩을 통해 입출력을 연결하는데, 입력 편집은 요청 파라메터에 연결하고 인메모리 테이블 필드는 출력 컨트롤에 연결한다. 이를 위해서는 디자인 시점에 HTTP 요청을 처리해야 하는데, RESTRequest 컴포넌트의 특정 명령을 사용하면 된다. 이렇게 하면 인메모리 테이블을 포함한 컴포넌트 메타데이터를 가져와서 적용할 수 있다. 이 작업을 완료하고 난 후, 라이브바인딩 디자이너에서 입력과 출력을 연결하고, 버튼을 눌러서 실행 코드를 넣어서 다음을 수행할 수 있다:

DataModule14.RESTRequest1.Execute();

 

다음은 라이브바인딩 디자이너의 모습이다:

spacer.png

 

마지막으로, 이 더운 여름 날씨를 보여주는 애플리케이션의 실행 모습이다:

spacer.png

 

결론

As you have seen, implementing a client for a REST API in Delphi is relatively simple (I already demonstrated the same in the past covering a different API here). Now in the case of a weather application there aren’t many alternatives compared to accessing live data from a web service, while in other scenarios using an API would be an alternative compared to embedding the same feature in a library part of the application.

지금까지 본 것과 같이, 델파이에서 REST API 클라이언트 구현은 비교적 간단하다 (다른 API를 다루는 동일한 데모를 이미 다룬 적이 있기도 하다). 날씨 애플리케이션의 경우, 웹 서비스의 실시간 데이터에 액세스하는 것은 다른 대안이 많지 않은 반면, API를 사용하는 다른 시나리오에서는 애플리케이션 라이브러리 부분에 동일한 기능을 내장하는 방법과 비교했을 때 대안이 될 수 있다.

We plan to showcase a few more of APILayer’s APIs on the Embarcadero blog, so stay tuned and feel free to share your ideas with us.

엠바카데로 블로그에서 APILayer의 API를 좀 더 선보일 예정이니, 앞으로도 지켜봐주시고 여러분의 아이디어도 자유롭게 공유할 수 있기를 바란다.

 

이 댓글 링크
다른 사이트에 공유하기

  • RAD changed the title to WeatherStack을 활용한 델파이 데모 (APILayer 사용)

이 토의에 참여하세요

지금 바로 의견을 남길 수 있습니다. 그리고 나서 가입해도 됩니다. 이미 회원이라면, 지금 로그인하고 본인 계정으로 의견을 남기세요.

Guest
이 토픽(기고/질문)에 답하기

×   서식있는 텍스트로 붙여넣기.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   이전에 작성한 콘텐츠가 복원되었습니다..   편집창 비우기

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

중요한 정보

이용약관 개인정보보호정책 이용규칙 이 사이트가 더 잘 작동하기 위해 방문자의 컴퓨터에 쿠키가 배치됩니다. 쿠키 설정 변경에서 원하는 설정을 할 수 있습니다. 변경하지 않으면 쿠키를 허용하는 것으로 이해합니다.