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!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

Top comments (0)

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay