# Sending Statistics

## URL

<mark style="color:red;">`GET`</mark> `https://api.smspartner.fr/v1/statistics/cost-resume?apiKey=API_KEY&interval=custom&from=21-10-2022&to=21-10-2022`

{% hint style="info" %}
Limit of 5 requests per minute.
{% endhint %}

#### **Required Parameters**

| Name       | Value                                                                                                                                                                                                                        |
| ---------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `apiKey`   | [Your API key](https://my.smspartner.fr/dashboard/api)                                                                                                                                                                       |
| `interval` | <ul><li><code>last\_month</code> → Previous month</li><li><code>last\_twelve\_months</code> → Last 12 months</li><li><code>custom</code> → Add <code>\&from=DD-MM-YYYY\&to=DD-MM-YYYY</code> for custom date range</li></ul> |

#### Requests

{% tabs %}
{% tab title="PHP" %}

```php
<?php
$apiKey = 'YOUR_API_KEY';
$url = 'https://api.smspartner.fr/v1/statistics/cost-resume?apiKey=' . $apiKey . '&interval=last_twelve_months'; 

// Initialise cURL session
$ch = curl_init($url);

// Set cURL options
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

// Execute cURL session and fetch the result
$response = curl_exec($ch);

// Handle errors
if (curl_errno($ch)) {
    echo 'Erreur: ' . curl_error($ch);
} else {
    // Decode the result
    $data = json_decode($response, true);
    print_r($data);
}

// Close cURL session
curl_close($ch);
?>
```

{% endtab %}

{% tab title="VB.net" %}

```vbnet
Imports System.IO
Imports System.Net
Imports System.Text

Module Module1

    Sub Main()
        Dim apiKey As String = "YOUR_API_KEY"
        Dim baseUrl As String = "https://api.smspartner.fr/v1/statistics/cost-resume"
        Dim url As String = baseUrl & "?apiKey=" & apiKey & "&interval=last_twelve_months"

        Dim response As String = apiRequest("GET", url, Nothing)
        Console.WriteLine(response)
    End Sub

    Function apiRequest(method As String, url As String, parameters As String) As String
        Dim request As HttpWebRequest = CType(WebRequest.Create(url), HttpWebRequest)
        request.Method = method
        request.Timeout = 10000 ' Timeout en ms
        request.ContentType = "application/json; charset=utf-8"

        ' Ajouter les paramètres si nécessaire (POST)
        If Not String.IsNullOrEmpty(parameters) Then
            request.ContentLength = Encoding.UTF8.GetByteCount(parameters)
            Using reqStream As StreamWriter = New StreamWriter(request.GetRequestStream())
                reqStream.Write(parameters)
            End Using
        End If

        ' Obtenir la réponse
        Try
            Using response As HttpWebResponse = CType(request.GetResponse(), HttpWebResponse)
                If response.StatusCode = HttpStatusCode.OK Then
                    Using resStream As Stream = response.GetResponseStream()
                        If resStream IsNot Nothing Then
                            Using reader As New StreamReader(resStream)
                                Return reader.ReadToEnd()
                            End Using
                        End If
                    End Using
                End If
            End Using
        Catch ex As WebException
            If ex.Response IsNot Nothing Then
                Using response As HttpWebResponse = CType(ex.Response, HttpWebResponse)
                    Using resStream As Stream = response.GetResponseStream()
                        If resStream IsNot Nothing Then
                            Using reader As New StreamReader(resStream)
                                Return "Erreur: " & reader.ReadToEnd()
                            End Using
                        End If
                    End Using
                End Using
            End If
            Return "Erreur: " & ex.Message
        End Try
    End Function

End Module
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

apiKey = 'YOUR_API_KEY'
url = f'https://api.smspartner.fr/v1/statistics/cost-resume?apiKey={apiKey}&interval=last_twelve_months'

try:
    response = requests.get(url)
    response.raise_for_status()
    data = response.json()
    print(data)
except requests.exceptions.RequestException as e:
    print(f"Erreur: {e}")


Ou avec la bibliothèque 'urllib':

import json
from urllib import request, error

apiKey = 'YOUR_API_KEY'
url = f'https://api.smspartner.fr/v1/statistics/cost-resume?apiKey={apiKey}&interval=last_twelve_months'

try:
    with request.urlopen(url) as response:
        data = json.load(response)
        print(data)
except error.URLError as e:
    print(f"Erreur: {e.reason}")
```

{% endtab %}

{% tab title="cURL" %}

```
curl -H "Content-Type: application/json" -X GET "https://api.smspartner.fr/v1/statistics/cost-resume?apiKey=YOUR_API_KEY&interval=last_twelve_months"
```

{% endtab %}

{% tab title="Nodejs" %}

```javascript
const https = require('https');

let apiKey = 'YOUR_API_KEY';
let url = `https://api.smspartner.fr/v1/statistics/cost-resume?apiKey=${apiKey}&interval=last_twelve_months`; // 12 derniers mois
//interval=last_month // 1 dernier mois
//interval=custom&from=21-10-2022&to=21-10-2022 // intervalle personnalisé

https.get(url, (res) => {
  let data = '';

  res.on('data', (chunk) => {
    data += chunk;
  });

  res.on('end', () => {
    console.log(JSON.parse(data));
  });

}).on("error", (err) => {
  console.log("Erreur: " + err.message);
});
```

{% endtab %}

{% tab title="JAVA" %}

```java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class StatistiqueDesEnvois {
    public static void main(String[] args) {
        try {
            // Prepare data for GET request
            String apiKey = "YOUR_API_KEY";
            String interval = "last_twelve_months";
            //interval=last_month // 1 dernier mois
//interval=custom&from=21-10-2022&to=21-10-2022 // intervalle personnalisé

            // Create GET request URL
            String urlString = "https://api.smspartner.fr/v1/statistics/cost-resume?" +
                    "apiKey=" + apiKey + "&interval=" + interval;

            // Create URL object
            URL url = new URL(urlString);

            // Create HTTP connection
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(10000);
            connection.setReadTimeout(10000);

            // Send GET request
            int responseCode = connection.getResponseCode();

            // Get response
            BufferedReader reader;
            if (responseCode >= 200 && responseCode <= 299) {
                reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            } else {
                reader = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
            }

            StringBuilder response = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            reader.close();

            // Process your response here
            System.out.println(response.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
```

{% endtab %}

{% tab title="Swift" %}

```swift
import SwiftUI

struct StatistiqueDesEnvois: View {
    @State private var result: String = "Loading..."

    var body: some View {
        VStack {
            Text("Statistique Des Envois")
                .font(.title)
                .padding()

            Text(result)
                .font(.system(size: 20))
                .padding()
        }
        .onAppear(perform: getStatistics)
    }

    func getStatistics() {
        let apiKey = "YOUR_API_KEY"
        let interval = "last_twelve_months"
        let urlString = "https://api.smspartner.fr/v1/statistics/cost-resume?apiKey=\(apiKey)&interval=\(interval)"

        guard let url = URL(string: urlString) else {
            print("Invalid URL")
            result = "Invalid URL"
            return
        }

        var request = URLRequest(url: url)
        request.httpMethod = "GET"

        let task = URLSession.shared.dataTask(with: request) { data, response, error in
            if let error = error {
                print("Error: \(error)")
                DispatchQueue.main.async {
                    self.result = "Error: \(error)"
                }
            } else if let data = data {
                let str = String(data: data, encoding: .utf8)
                DispatchQueue.main.async {
                    self.result = str ?? "Error"
                }
            }
        }

        task.resume()
    }
}
```

{% endtab %}

{% tab title="Go" %}

```go
package main

import (
	"io/ioutil"
	"log"
	"net/http"
	"time"
)

func main() {
	// Prepare data for GET request
	apiKey := "YOUR_API_KEY"
	interval := "last_twelve_months" // last month: "last_month", custom interval: "custom&from=21-10-2022&to=21-10-2022"

	// Create GET request URL
	url := "https://api.smspartner.fr/v1/statistics/cost-resume?" +
		"apiKey=" + apiKey + "&interval=" + interval

	// Create HTTP client
	client := &http.Client{Timeout: 10 * time.Second}

	// Send GET request
	resp, err := client.Get(url)
	if err != nil {
		log.Fatalf("Error sending request: %v", err)
	}
	defer resp.Body.Close()

	// Get response
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		log.Fatalf("Error reading response body: %v", err)
	}

	// Process your response here
	log.Printf("Response: %s", body)
}
```

{% endtab %}

{% tab title="C#" %}

```csharp
using System;
using System.Net.Http;
using System.Threading.Tasks;

class Program
{
    private static readonly HttpClient client = new HttpClient();

    static async Task Main(string[] args)
    {
        var apiKey = "VOTRE_CLÉ_API";
        var interval = "last_twelve_months"; // Changer à "last_month" pour le dernier mois, "custom" pour un intervalle personnalisé
        var uri = new Uri($"https://api.smspartner.fr/v1/statistics/cost-resume?apiKey={apiKey}&interval={interval}"); // Ajoutez "&from=date&to=date" pour un intervalle personnalisé

        // Envoyer la requête GET
        HttpResponseMessage response = await client.GetAsync(uri);

        if (response.IsSuccessStatusCode)
        {
            // Lire la réponse
            var result = await response.Content.ReadAsStringAsync();
            Console.WriteLine(result);
        }
        else
        {
            // Afficher un message en cas d'échec de la requête GET
            Console.WriteLine("La requête GET a échoué avec le code de statut: " + response.StatusCode);
        }
    }
}
```

{% endtab %}
{% endtabs %}

#### **Response**

{% tabs %}
{% tab title="json" %}
{% code fullWidth="true" %}

```json
{
    "success": true,
    "datas": [
        {
            "month": "october",
            "year": "2021",
            "m": "10",
            "date": 1633039200,
            "type": "month",
            "cost": "49.174",
            "nb_send": "1210"
        },
        {
            "month": "november",
            "year": "2021",
            "m": "11",
            "date": 1635721200,
            "type": "month",
            "cost": "67.674",
            "nb_send": "1409"
        }
    ]
}
```

{% endcode %}
{% endtab %}
{% endtabs %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://www.docpartner.dev/en/api/sms-partner/status-and-statistics/sending-statistics.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
