DEV Community

Ali Buğra Okkalı for Açıklab

Posted on • Edited on

5

Liman MYS üzerinde API kullanımı

Public API Kullanım Örneği

Bu yazıda public bir API'nin Liman eklentisinde nasıl kullanılabileceğinden bahsedeceğim.

Kodlara linkten ulaşabilirsiniz. https://github.com/abugraokkali/Liman-Covid-Stats

  • app/Controllers/ApiController.php
  use GuzzleHttp\Client;
Enter fullscreen mode Exit fullscreen mode

İlk olarak dosyamızda GuzzleHttp\Client kullanacağımızı belirtiyoruz.

Guzzle, HTTP isteklerini göndermeyi ve web servisleriyle entegre olmayı kolaylaştıran bir PHP HTTP istemcisidir. Özet bir bilgiye gist yazımdan ulaşabilirsiniz.

https://gist.github.com/abugraokkali/8d99177a7af4daa62b2d63e3941fdd88

  public function getResponse()
  {
    $client = new GuzzleHttp\Client(
        ['base_uri' => 'https://api.covid19api.com/']
    );
    $response = $client->request('GET', 'summary');
    return json_decode($response->getBody()->getContents());

  }
Enter fullscreen mode Exit fullscreen mode

Base URI'yı https://api.covid19api.com/ olan bir GuzzleHttp\Client objesi oluşturuyoruz. Request'lerimizi bu client üzerinden yapacağız.

Client nesnesinin request methoduyla /summary enpoint'ine GET sorgusu yapıyoruz. JSON formatındaki response'unu decode edip return ediyoruz.

Request : GET https://api.covid19api.com/summary

Response :

  {
    "ID": "17cf60ab-05a9-4a5d-8027-458354300853",
    "Message": "",
    "Global": {
      "NewConfirmed": 306062,
      "TotalConfirmed": 205102230,
      "NewDeaths": 3858,
      "TotalDeaths": 4331537,
      "NewRecovered": 0,
      "TotalRecovered": 0,
      "Date": "2021-08-13T07:08:37.28Z"
    },
    "Countries": [
      ...
      {
        "ID": "b1cecf17-faac-4e60-b5e3-9266759234a6",
        "Country": "Turkey",
        "CountryCode": "TR",
        "Slug": "turkey",
        "NewConfirmed": 0,
        "TotalConfirmed": 6018455,
        "NewDeaths": 0,
        "TotalDeaths": 52703,
        "NewRecovered": 0,
        "TotalRecovered": 0,
        "Date": "2021-08-13T07:08:37.28Z",
        "Premium": {}
      },
      ...
     ],
    "Date": "2021-08-13T07:08:37.28Z"
   }
Enter fullscreen mode Exit fullscreen mode
  public function listCountries()
  {
      $response = $this->getResponse();
      $countries = (array) $response->{'Countries'};
      $data = [];
    foreach($countries as $country){
        $data[] = [
            "Country" => $country->{'Country'},
            "CountryCode" => $country->{'CountryCode'},
            "TotalConfirmed" => $country->{'TotalConfirmed'},
            "TotalDeaths" => $country->{'TotalDeaths'},
        ];
    }
    return view('table', [
        "value" => $data,
        "title" => ["Ülke","Ülke Kodu","Vaka Sayısı","Vefat Sayısı"],
        "display" => ["Country","CountryCode","TotalConfirmed","TotalDeaths"]
    ]);

  }
Enter fullscreen mode Exit fullscreen mode

Bu fonksiyon getResponse()'un çağrılıp verinin istenen formata dönüştürülmesi işini yapıyor.

Özetle;

  • getResponse() çağırılıyor,
  • getResponse()'un return ettiği response'un {'Countries'} attribute'u alınıyor ve array haline getiriliyor,

  • array üzerinden for-loop ile geçiliyor ve istenen attribute'lar data adında bir array'de tutuluyor,

  • data array'i view'e parametre olarak verilip

return ediliyor.

  • routes.php
<?php
return [
  ...
  "list_countries" => "ApiController@listCountries",
  ...
];
Enter fullscreen mode Exit fullscreen mode
  • views/countries/main.blade
<div class="row">
    <div class="col-12 mb-2">
        <div class="table-responsive" id="countriesTable"></div>
    </div>
</div>

@include("countries.scripts")
Enter fullscreen mode Exit fullscreen mode

Tablo için bir div oluşturuyoruz.

  • views/countries/scripts.blade
<script>
    function listCountries(){
        showSwal("{{__('Yükleniyor...')}}", 'info');
        let data = new FormData();
        request("{{API('list_countries')}}", data, function(response){
            $('#countriesTable').html(response).find('table').DataTable(
                                                              dataTablePresets('normal');
            Swal.close();
        }, function(response){
            response = JSON.parse(response);
            showSwal(response.message, 'error');
        });
    }
</script>
Enter fullscreen mode Exit fullscreen mode

Return edilen view'i oluşturduğumuz div'e koyuyoruz ve tabloyu bastırmış oluyoruz.

Alt Text

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more