Skip to content

Instantly share code, notes, and snippets.

@temp3l
Last active August 26, 2019 18:40
Show Gist options
  • Save temp3l/fa18b203acdaec6e598471ee8a2e9da7 to your computer and use it in GitHub Desktop.
Save temp3l/fa18b203acdaec6e598471ee8a2e9da7 to your computer and use it in GitHub Desktop.

export { themes } from './theme2'; import { Appear, Image } from '@mdx-deck/components'; import { Invert, Split, SplitRight, FullScreenCode, Horizontal } from 'mdx-deck/layouts' import { CodeSurferLayout } from 'code-surfer'; import { RandomlyPlaced } from './components/RandomlyPlaced'; import { SlideIn, BlurIn, ZoomSteps } from './components/lib'; import TerminalFramed from './components/TerminalFramed'; import { TerminalStyle } from './components/layout/layout'; import {Coder} from './components/Coder' import SchemaSurferSimple from './components/schema-surfer-simple.mdx'; import './global.css';

DDD-LD



api-middleware-award


Gute API

  • fachliche Konzepte und Dienste nach außen kommunizieren
  • leicht verständlich für Client-Entwicker
  • maschinenverständlich

GET /events/4711
{
  "id": "4711",
  "start": "2019-03-28 21:00",
  "movie_id": 14123,
  "movie_name": "Aquaman",
  "image": "static/images/aquaman.png",
  "price": 1600,
  "location_id": "123",
  "tickets_left": 120,
  "rebate_tariff": "A-12",
  "promote": true
}

Böse API

  • vermischt mehrere Domänenkonzepte
         → Ausstrahlungstermin, Film, Preise, Verfügbarkeiten
  • technische Flags, ohne klare fachliche Bedeutung
        → hidden, available, promote
  • Es ist unklar, ob und wie weitere Daten abgerufen werden können
        → z.B. Filmdetails
  • exponiert interne Identifier
         → id, rebate_tariff, location_id

API - fachliche Entitäten bereitstellen

  • Filme
  • Vorstellungstermine
  • Kinos
  • Preise / Angebote
  • Verfügbarkeiten

API - Services bereitstellen

  • Vorstellungstermine zu Filmen suchen
  • Angebote einsehen
  • Tickets buchen
  • Platzreservierung vornehmen

Better API

Entität Schema-URI
Film http://schema.org/Movie
Vorstellungstermin http://schema.org/ScreeningEvent
Angebot http://schema.org/Offer
Sitzplatz http://schema.org/Seat
Versicherung http://schema.org/InsuranceAgency
givenName http://schema.org/givenName
Ding http://schema.org/Thing

  • Schema.org is a joint effort between Google, Microsoft, Yahoo!, and Yandex
  • Selbst in hoch-innovativen Geschäftsfeldern => allgemeine Konzepte
  •       Preise
  •       Personen
  •       Orte
  • Eindeutige URIs zur Auszeichnung von Daten
  • Inhalte aus Webseiten für Suchmaschinen verständlich machen
  • Nutzung von Schema.org in APIs mittles JSON-LD Repräsentation

„classic“ JSON pitfalls

  • Neue Backend-Version...
  • andere JSON-Bezeichner
  • Strukturen werden geändert
  • Daten werden nicht mehr direkt ausgeliefert
  • ... erfordern zusätzliche HTTP-Anfrage(n)

current Challenge

  • Java => CamelCase
  • openAPI => snake_case
  • kebab-case => url-case
  • PascalCase => ClassCase
  • first_name
  • first-name
  • firstName
  • firstname
  • FirstName
  • Vorname, VorName, Vor_name, ...
  • ... дата рождения

application/ld+json

  • Erweiterung der Daten im Backend um einen "Kontext"
  • Dieser Kontext beschreibt die Semantik der Daten

{
  "firstname": "John",
  "lastname":  "Doe",
  "birthday":  "1978-05-17"
}
{
  "@context": {
    "@vocab": "https://schema.org/",
    "firstname": "givenName",
    "lastname":  "familyName",
    "birthday":  "birthDate"
  },

  "firstname": "John",
  "lastname":  "Doe",
  "birthday":  "1978-05-17"
}

{
  "@vocab": "https://schema.org/",
  "first_name": "givenName",
  "last_name":  "familyName",
  "дата_рождения": "birthDate"
}
{
  "http://schema.org/givenName":   "Steph Reb",
  "http://schema.org/url":   { "@id": "http://steph.reb.org/" },
  "http://schema.org/image": { "@id": "http://steph.reb.org/images/steph.png" }

  // The '@id' keyword means 'This value is an identifier that is an IRI'
}
{
  "@context": "https://schema.org",
  "@type": "NewsArticle",
  "image": [
    "https://example.com/photos/1x1/photo.jpg",
    "https://example.com/photos/4x3/photo.jpg",
    "https://example.com/photos/16x9/photo.jpg"
  ]
}

JSON-LD

  • from existing JSON-based services to self-descriptive services
  • expressing Linked Data in JSON
  • adding semantics to existing JSON
  • provides context, metadata, and a standard graph traversal mechanism
  • give JSON messages a well-defined meaning by mapping most things to IRIs
  • build interoperable Web Services (no RDF)
  •  
  • fachliche Konzepte in Form von klassischem JSON darstellen

Benefits

  • Änderungen im Backend ohne Auswirkung auf Clients
  • Entkopplung FrontEnd / Backend
  • ... solange verwendete Semantik die gleiche bleibt
  • Team focus auf:
  • fachlich wichtige Semantik des Datenaustauschs (Fachliche Bedeutung)
  • statt auf „Camel- vs. Snake-Case“

Downsides

  • Missing: profile to specify field names and data-structure

    • a few well-known and widely adopted profiles will emerge
  • Multiple ways to serialize the same graph data

    • JSON-only clients depend on structure and not directly on the semantics of the serialization

JSON-LD vs JSON-Schema

JSON-LD

  • give JSON messages a well-defined meaning by mapping most things to IRIs
  • adding semantics to existing JSON

JSON-Schema

  • describes the syntactic structure of a JSON document
  • validate

FOAF - Friend Of A Friend

  • machine-readable ontology, describing:

    • persons
    • their activities
    • their relations to other people and objects.
  • allows groups of people to describe social networks without a centralised database

  • loosely-coupled collection of Data (=> LOD Cloud)


{ 
  "@context": {
    "foaf": "http://xmlns.com/foaf/0.1/"
  },
  "@graph": [
    {
      "@type": "foaf:Person",
      "foaf:homepage": "http://example.com/bob/",
      "foaf:name": "Bob"
    }
  ]
}
{
  "@vocab": "http://xmlns.com/foaf/0.1/",

  "@context": {
    "name": "http://xmlns.com/foaf/0.1/name",
    "knows": "http://xmlns.com/foaf/0.1/knows"
  },
  // triplets: subject => prädikat => object

  "name": "Markus Lanthaler",
  "knows": {
    "@id": "/people/john",
    "name": "John Doe"
  }
}

triples

  1. http://example.name#Bob
  2. http://xmlns.com/foaf/0.1/knows
  3. http://example.name#John
  • precise representation
  • semantic data can be unambiguously queried and reasoned about.

<ul>
  <li>
    <a href="http://example.com/bob/">
      <span>Bob</span>
    </a>
  </li>
</ul>
<div prefix="foaf: http://xmlns.com/foaf/0.1/">
  <ul>
    <li typeof="foaf:Person">
      <a property="foaf:homepage" href="http://example.com/bob/">
        <span property="foaf:name">Bob</span>
      </a>
    </li>
  </ul>
</div>

The Web is a giant graph of knowledge ( distributed hypermedia system )

Regardless of whether information is in:

  • people's heads
  • in physical or digital documents
  • or in the form of factual data

it can be linked


<img src="./images/lod2011.png" alt="lod2011" style={{background: 'white', height:'100vh'}} />


<img src="./images/lod2019.png" alt="lod2011" style={{background: 'white', height:'100vh'}} />


<img src="./images/nextql_dream.png" alt="Image alt" style={{background: 'white', height:'80vh'}} />


Model Your Application Domain, Not Your JSON Structures


Data-Modeling / RDF

  • dramatically simplified reuse of domain models
  • formal description of entities properties and relationships in the problem domain
  • reduces the costs and risks
  • benefits in terms of interoperability and adoption
  • its schemalessness ensures the required agility in today’s fast-moving world
  • JSON-LD: the simplicity of JSON with the semantic expressivity of RDF

Behavioral Modeling

  • Hydra, a lightweight vocabulary to capture and document the behavioral model of hypermedia-driven Web APIs in a machine-processable way.
  • describe the domain application protocol of services.
  • document semantics of specific HTTP operations
  • combination of formal data model + holistic documentation of behavioral model (in a unified form)
  • enables the creation of declarative contracts capturing all aspects of a Web APIs.

data-modeling-is-dead-long-live-schema


openAPI

Models


Guidelines


Network-based Software Architectures


Error Handling


// https://github.com/Microsoft/api-guidelines/blob/master/Guidelines.md#51-errors
{ "error": {
    "code": "BadArgument",
    "message": "Multiple errors in ContactInfo data",
    "target": "ContactInfo",
    "details": [{ "code": "NullValue", "target": "PhoneNumber", "message": "Phone number must not be null" } ]
}}
// https://github.com/CiscoDevNet/api-design-guide/blob/master/README.md
{ "error" : {
  "key" : "404",
        "message" : [
            "File kittens.jpg not found.",
            "Database connection failure."
        ]
    },
    "trackingId" : "S1_12345678-90ab-cdef-1234-567890abcdef_0" }
// https://github.com/cloudfoundry/cc-api-v3-style-guide#errors
{ "errors": [
    {
       "detail": "Relationships is not a hash.",
       "title": "CF-UnprocessableEntity",
       "code": 10008
    }
  ]
}

  • detail:
    • User-readable message describing the error.
    • Intended to be surfaced by clients to users.
  • title:
    • Human-readable unique descriptor for the class of error.
  • code:
    • Numerical, unique identifier for the class of error.

Codes

https://github.com/strongloop/loopback-next/blob/master/docs/site/Controllers.md

  • 400 BadRequest
  • 401 Unauthorized
  • 403 Forbidden
  • 404 NotFound
  • 500 InternalServerError
  • 502 BadGateway
  • 503 ServiceUnavailable
  • 504 GatewayTimeout
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment