Écritures
Le réseau coupe et deux programmes peuvent modifier la même chose.
Une Idempotency-Key rend un nouvel essai sans danger ;
If-Match vous empêche d'écraser un changement que vous
n'avez pas vu.
Créer
CLI
#!/usr/bin/env bash
# writes-create: the myle CLI (key from `myle login` or MYLE_API_KEY).
# The CLI generates an Idempotency-Key for a POST and reuses it on every retry.
# Pass --idempotency-key to choose it, to stay safe across runs too.
answer=$(myle products create --organization organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d \
--number A0042 --name 'Paille de blé, botte' --vat-rate 10 \
-d 'unitPrice[amount]=4.50' -d 'unitPrice[currency]=EUR' \
-d 'accountingNumber:=null' --tags Fourrage -i --format json)
# -i --format json prints one object: {status, headers, body}.
jq -r .body.id <<<"$answer" # the new id
jq -r .headers.etag <<<"$answer" # and its ETag: "1"
HTTP (curl)
curl https://api.myleapp.fr/organizations/organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d/products \
-H "Authorization: Bearer $MYLE_API_KEY" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: 6f1c2a9e-0b7d-4f7a-9a51-1d2b3c4d5e6f" \
-d '{
"number": "A0042",
"name": "Paille de blé, botte",
"unitPrice": { "amount": "4.50", "currency": "EUR" },
"vatRate": "10",
"accountingNumber": null,
"tags": ["Fourrage"]
}'
TypeScript
import { Myle } from '@myleapp/myle';
const myle = new Myle();
const products = myle.organization('organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d').products;
// The SDK generates an Idempotency-Key for the call and reuses it on every retry.
// Pass { idempotencyKey } to choose it, to stay safe across runs too.
const product = await products.create({
number: 'A0042',
name: 'Paille de blé, botte',
unitPrice: { amount: '4.50', currency: 'EUR' },
vatRate: '10',
accountingNumber: null,
tags: ['Fourrage'],
});
console.log(product.id, product.etag); // the new id, and its ETag: "1"
Python
from myle import Myle
myle = Myle()
products = myle.organization("organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d").products
# The SDK generates an Idempotency-Key for the call and reuses it on every retry.
# Pass idempotency_key= to choose it, to stay safe across runs too.
product = products.create(
number="A0042",
name="Paille de blé, botte",
unit_price={"amount": "4.50", "currency": "EUR"},
vat_rate="10",
accounting_number=None,
tags=["Fourrage"],
)
print(product.id, product.etag) # the new id, and its ETag: "1"
Go
package main
import (
"context"
"fmt"
"log"
myle "github.com/myleapp/myle-go"
)
func main() {
client := myle.NewClient()
products := client.Organization("organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d").Products
// The SDK generates an Idempotency-Key for the call and reuses it on every retry.
// Pass myle.IdempotencyKey(…) to choose it, to stay safe across runs too.
product, err := products.Create(context.Background(), &myle.ProductCreateParams{
Number: "A0042",
Name: "Paille de blé, botte",
UnitPrice: myle.Value(myle.Money{Amount: "4.50", Currency: "EUR"}),
VatRate: "10",
AccountingNumber: myle.Null[string](),
Tags: myle.Value([]string{"Fourrage"}),
})
if err != nil {
log.Fatal(err)
}
fmt.Println(product.ID, product.ETag()) // the new id, and its ETag: "1"
}
Java
import fr.myleapp.myle.Money;
import fr.myleapp.myle.MyleClient;
import fr.myleapp.myle.Product;
import fr.myleapp.myle.ProductCreateParams;
import fr.myleapp.myle.Products;
import java.util.List;
public class Example {
public static void main(String[] args) {
MyleClient client = MyleClient.builder().build();
Products products = client.organization("organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d").products();
// The SDK generates an Idempotency-Key for the call and reuses it on every retry.
// Pass RequestOptions.builder().idempotencyKey(...) to choose it, to stay safe across runs too.
Product product = products.create(ProductCreateParams.builder()
.number("A0042")
.name("Paille de blé, botte")
.unitPrice(new Money("4.50", "EUR"))
.vatRate("10")
.accountingNumber(null)
.tags(List.of("Fourrage"))
.build());
System.out.println(product.id() + " " + product.etag()); // the new id, and its ETag: "1"
}
}
Scala
import fr.myleapp.myle.MyleClient
import fr.myleapp.myle.models.{CreateProduct, Money}
object WritesCreate {
def main(args: Array[String]): Unit = {
val myle = MyleClient()
val products = myle.organization("organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d").products
// The SDK generates an Idempotency-Key for the call and reuses it on every retry.
// Pass idempotencyKey = Some(…) to choose it, to stay safe across runs too.
val product = products.create(
CreateProduct(
number = "A0042",
name = "Paille de blé, botte",
unitPrice = Some(Money(amount = "4.50", currency = "EUR")),
vatRate = "10",
accountingNumber = None, // None: left out
tags = Some(List("Fourrage"))
)
)
println(s"${product.id} ${product.etag.getOrElse("")}") // the new id, and its ETag: "1"
}
}
PHP
<?php
require __DIR__ . '/vendor/autoload.php';
use Myle\Client;
$myle = new Client();
$products = $myle->organization('organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d')->products;
// The SDK generates an Idempotency-Key for the call and reuses it on every retry.
// Pass idempotencyKey: to choose it, to stay safe across runs too.
$product = $products->create(
number: 'A0042',
name: 'Paille de blé, botte',
unitPrice: ['amount' => '4.50', 'currency' => 'EUR'],
vatRate: '10',
accountingNumber: null,
tags: ['Fourrage'],
);
echo $product->id, ' ', $product->etag(), "\n"; // the new id, and its ETag: "1"
C#
using Myle;
using var client = new MyleClient();
var products = client.Organization("organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d").Products;
// The SDK generates an Idempotency-Key for the call and reuses it on every retry.
// Set RequestOptions.IdempotencyKey to choose it, to stay safe across runs too.
var product = await products.CreateAsync(new ProductCreateParams
{
Number = "A0042",
Name = "Paille de blé, botte",
UnitPrice = new Money { Amount = "4.50", Currency = "EUR" },
VatRate = "10",
AccountingNumber = null,
Tags = ["Fourrage"],
});
Console.WriteLine($"{product.Id} {product.ETag}"); // the new id, and its ETag: "1"
HTTP
HTTP/1.1 201 Created
Location: /organizations/organization_7f2c…/products/product_51c3…
ETag: "1"
Myle-Request-Id: 01M803CAJ14DSK72C4MKMWBPT7
RateLimit-Policy: "write";q=120;w=60
RateLimit: "write";r=119;t=60
{ "id": "product_51c3…", "object": "product", "number": "A0042", "…": "…" }
Une création répond 201, la ressource, son chemin dans
Location et son ETag.
Clés d'idempotence
Si la connexion coupe après l'envoi d'un POST, vous ne
pouvez pas savoir si Myle l'a reçu. Envoyez une
Idempotency-Key et réessayez avec la même : Myle ne fait
le travail qu'une fois.
-
La clé est à vous de la choisir : de 1 à 255 caractères ASCII
visibles. Un UUID par opération est le plus simple ; une clé tirée
de votre propre identifiant (
shop-order-1234) convient aussi. -
Même clé, même requête (méthode, chemin et octets du corps) : Myle
rejoue la première réponse, avec son statut, son corps, son
Locationet sonETag, plusMyle-Idempotent-Replayed: trueet un nouveauMyle-Request-Id. Rien n'est créé deux fois. - Même clé, autre corps :
422 core.idempotency-key-reused. -
La première requête encore en cours : le nouvel essai attend sa
réponse ; au bout de 10 secondes, il répond
409 core.idempotency-key-in-useavecRetry-After. - Une clé est gardée 24 heures et appartient à la clé d'API qui l'a envoyée : deux clés d'API n'en partagent jamais une.
-
Un refus de l'opération elle-même (un
409, un412) est gardé et rejoué comme un succès. Une erreur du serveur (5xx), ou un refus avant que l'opération ne s'exécute (authentification, droits, corps illisible), ne garde rien : le nouvel essai s'exécute pour de bon.
Les opérations qui acceptent une Idempotency-Key le
disent dans la référence ; toutes les créations le font.
Modifier : PATCH avec un merge patch
Un PATCH n'envoie que ce qui change, sous forme de JSON
merge patch (RFC 7396), avec
Content-Type: application/merge-patch+json. Un membre à
null est vidé ; un membre absent reste tel quel.
CLI
#!/usr/bin/env bash
# writes-patch: the myle CLI (key from `myle login` or MYLE_API_KEY).
org=organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d
product=product_51c3a7e2-6d4b-4f8a-b1c9-0e2d3f4a5b6c
etag=$(myle products retrieve "$product" --organization "$org" -i --format json | jq -r .headers.etag)
# A merge patch: only what you pass changes, := null clears a member.
# --if-match takes the ETag as you read it: 412 if the product changed since.
myle products update "$product" --organization "$org" \
-d 'unitPrice[amount]=4.80' -d 'unitPrice[currency]=EUR' -d 'tags:=null' \
--if-match "$etag" \
| jq -c .unitPrice
HTTP (curl)
curl -X PATCH https://api.myleapp.fr/organizations/organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d/products/product_51c3a7e2-6d4b-4f8a-b1c9-0e2d3f4a5b6c \
-H "Authorization: Bearer $MYLE_API_KEY" \
-H "Content-Type: application/merge-patch+json" \
-H 'If-Match: "1"' \
-d '{ "unitPrice": { "amount": "4.80", "currency": "EUR" }, "tags": null }'
TypeScript
import { Myle } from '@myleapp/myle';
const myle = new Myle();
const products = myle.organization('organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d').products;
const product = await products.get('product_51c3a7e2-6d4b-4f8a-b1c9-0e2d3f4a5b6c');
// A merge patch: only what you pass changes, null clears a member.
// ifMatch takes the product as you read it (or its etag): 412 if it changed since.
const updated = await products.update(
product.id,
{ unitPrice: { amount: '4.80', currency: 'EUR' }, tags: null },
{ ifMatch: product },
);
console.log(updated.unitPrice, updated.etag);
Python
from myle import Myle
myle = Myle()
products = myle.organization("organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d").products
product = products.get("product_51c3a7e2-6d4b-4f8a-b1c9-0e2d3f4a5b6c")
# A merge patch: only what you pass changes, None clears a member.
# if_match takes the product as you read it (or its etag): 412 if it changed since.
updated = products.update(
product.id,
unit_price={"amount": "4.80", "currency": "EUR"},
tags=None,
if_match=product,
)
print(updated.unit_price, updated.etag)
Go
package main
import (
"context"
"fmt"
"log"
myle "github.com/myleapp/myle-go"
)
func main() {
client := myle.NewClient()
products := client.Organization("organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d").Products
ctx := context.Background()
product, err := products.Get(ctx, "product_51c3a7e2-6d4b-4f8a-b1c9-0e2d3f4a5b6c")
if err != nil {
log.Fatal(err)
}
// A merge patch: only what you pass changes, myle.Null clears a member.
// IfMatch takes the product as you read it (or its ETag): 412 if it changed since.
updated, err := products.Update(ctx, product.ID, &myle.ProductUpdateParams{
UnitPrice: myle.Value(myle.Money{Amount: "4.80", Currency: "EUR"}),
Tags: myle.Null[[]string](),
}, myle.IfMatch(product))
if err != nil {
log.Fatal(err)
}
fmt.Println(updated.UnitPrice.Amount, updated.ETag())
}
Java
import fr.myleapp.myle.Money;
import fr.myleapp.myle.MyleClient;
import fr.myleapp.myle.Product;
import fr.myleapp.myle.ProductUpdateParams;
import fr.myleapp.myle.Products;
import fr.myleapp.myle.RequestOptions;
public class Example {
public static void main(String[] args) {
MyleClient client = MyleClient.builder().build();
Products products = client.organization("organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d").products();
Product product = products.get("product_51c3a7e2-6d4b-4f8a-b1c9-0e2d3f4a5b6c");
// A merge patch: only what you set changes, null clears a member.
// ifMatch takes the product as you read it (or its etag): 412 if it changed since.
Product updated = products.update(product.id(),
ProductUpdateParams.builder().unitPrice(new Money("4.80", "EUR")).tags(null).build(),
RequestOptions.builder().ifMatch(product).build());
System.out.println(updated.unitPrice().amount() + " " + updated.unitPrice().currency() + " " + updated.etag());
}
}
Scala
import fr.myleapp.myle.{IfMatch, MyleClient, Patch}
import fr.myleapp.myle.models.{Money, UpdateProduct}
object WritesPatch {
def main(args: Array[String]): Unit = {
val myle = MyleClient()
val products = myle.organization("organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d").products
val product = products.get("product_51c3a7e2-6d4b-4f8a-b1c9-0e2d3f4a5b6c")
// A merge patch: only what you set changes, Patch.Null clears a member.
// ifMatch takes the product as you read it (or its etag): 412 if it changed since.
val updated = products.update(
product.id,
UpdateProduct(unitPrice = Patch(Money(amount = "4.80", currency = "EUR")), tags = Patch.Null),
ifMatch = IfMatch(product)
)
println(s"${updated.unitPrice} ${updated.etag.getOrElse("")}")
}
}
PHP
<?php
require __DIR__ . '/vendor/autoload.php';
use Myle\Client;
$myle = new Client();
$products = $myle->organization('organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d')->products;
$product = $products->get('product_51c3a7e2-6d4b-4f8a-b1c9-0e2d3f4a5b6c');
// A merge patch: only what you pass changes, null clears a member.
// ifMatch takes the product as you read it (or its etag): 412 if it changed since.
$updated = $products->update(
$product->id,
unitPrice: ['amount' => '4.80', 'currency' => 'EUR'],
tags: null,
ifMatch: $product,
);
echo json_encode($updated->unitPrice), ' ', $updated->etag(), "\n";
C#
using Myle;
using var client = new MyleClient();
var products = client.Organization("organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d").Products;
var product = await products.GetAsync("product_51c3a7e2-6d4b-4f8a-b1c9-0e2d3f4a5b6c");
// A merge patch: only what you set changes, null clears a member.
// IfMatch takes the product as you read it (or its ETag): 412 if it changed since.
var updated = await products.UpdateAsync(
product.Id,
new ProductUpdateParams { UnitPrice = new Money { Amount = "4.80", Currency = "EUR" }, Tags = null },
new RequestOptions { IfMatch = product });
Console.WriteLine($"{updated.UnitPrice} {updated.ETag}");
ETag et If-Match
- Chaque ressource seule répond un
ETag, qui change avec elle. -
Renvoyez-le dans
If-Matchsur unPATCHou unDELETE. Si la ressource a changé depuis votre lecture, Myle refuse avec412 core.precondition-failed: relisez-la, fusionnez, et réessayez avec le nouvelETag. -
Sans
If-Match(ou avec*), la modification s'applique quoi qu'il se soit passé entre-temps : la dernière écriture l'emporte.
À venir. If-None-Match sur un
GET, qui répond 304 Not Modified quand
rien n'a changé, est conçu mais pas encore construit.
Supprimer
DELETE répond 204 sans corps, et respecte
If-Match. Une ressource supprimée répond ensuite
404.
Lots
Un lot est POST …/<collection>/batch-<verbe>
avec {"ids": […]}, aujourd'hui
POST /organizations/{id}/invoices/batch-validate
(jusqu'à 1000 factures). Il répond 200 avec un résultat
par id, dans l'ordre envoyé : un échec partiel n'est pas une erreur
HTTP. Chaque résultat est SUCCEEDED, ou
FAILED avec l'erreur que cet élément aurait répondue seul
(code, context, error, sans
request_id) ; les autres sont passés quand même.
JSON
{
"data": [
{ "id": "invoice_3f1c9a2e-7b4d-4e8a-9c6f-1a2b3c4d5e6f", "status": "SUCCEEDED", "error": null },
{ "id": "invoice_8e7d6c5b-4a3f-4e2d-b1c0-9f8e7d6c5b4a", "status": "FAILED",
"error": { "code": "billing.invoice.not-a-draft",
"context": { "status": "PAID" },
"error": "Cette facture n'est plus un brouillon (PAID) : annulez-la ou corrigez-la par un avoir." } }
]
}
Tâches asynchrones
À venir. Aucune opération ne répond encore
202. Une opération longue répondra
202 Accepted, avec
Location: /organizations/{id}/jobs/{jobId} et
Retry-After, et une tâche à relire à cette adresse
jusqu'à ce que son status soit définitif :
JSON
{ "id": "job_…", "object": "job", "status": "RUNNING", "result": null, "createdAt": "…" }