Writes

Networks fail and two programs can change the same thing. An Idempotency-Key makes a retry safe; If-Match keeps you from overwriting a change you have not seen.

Create

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", "…": "…" }

A creation answers 201, the resource, its path in Location and its ETag.

Idempotency keys

If the connection drops after you sent a POST, you cannot know whether Myle received it. Send an Idempotency-Key and retry with the same one: Myle does the work once.

Operations that accept an Idempotency-Key say so in the reference; every creation does.

Change: PATCH with a merge patch

A PATCH sends only what changes, as a JSON merge patch (RFC 7396), with Content-Type: application/merge-patch+json. A member set to null is cleared; an absent member is left as it is.

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 and If-Match

Coming. If-None-Match on a GET, answering 304 Not Modified when nothing changed, is designed but not built yet.

Delete

DELETE answers 204 with no body, and honors If-Match. A deleted resource answers 404 afterwards.

Batches

A batch is POST …/<collection>/batch-<verb> with {"ids": […]}, today POST /organizations/{id}/invoices/batch-validate (up to 1000 invoices). It answers 200 with one result per id, in the order sent: a partial failure is not an HTTP error. Each result is SUCCEEDED, or FAILED with the error that item would have answered alone (code, context, error, without request_id); the others went through all the same.

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": "This invoice is no longer a draft (PAID): cancel or correct it with a credit note." } }
  ]
}

Asynchronous jobs

Coming. No operation answers 202 yet. A long operation will answer 202 Accepted, with Location: /organizations/{id}/jobs/{jobId} and Retry-After, and a job you read at that address until its status is final:

JSON

{ "id": "job_…", "object": "job", "status": "RUNNING", "result": null, "createdAt": "…" }