Kuidas kasutada API-esmaseid platvorme oma veebisaitide kiiremaks ülesehitamiseks

Kuidas kasutada API-esmaseid platvorme oma veebisaitide kiiremaks ülesehitamiseks

Tööriistad nagu Jekyll, Hugo või Hexo on viimastel aastatel staatilisi veebisaite populariseerinud. Niinimetatud JAMstack võimaldab teil edastada ülidünaamilist sisu, millel pole üldse tagakihti. Lisaks võimaldasid arendaja esimesed API-d kasutajaliidese arendajatel luua veelgi keerukama funktsionaalsuse. Seda saavad nad teha brauseri liivakastist lahkumata. Vaatame, kuidas saate ärirakenduse kindla prototüübi edastamiseks kasutada kaasaegseid API-esmaseid platvorme. Selles artiklis toodud lähenemisviis võib teie lahendiarhitekti tööriistakomplektis olla kasulik vara.

Õpetus koosneb kahest osast:

  • Esimene näitab teile, kuidas kujundada rakendus nn õnneliku tee saamiseks. Ehitame poolautomaatse prototüübi, mida saate kasutada demoseansi kohta kasutajate tagasiside saamiseks
  • Teises selgitatakse, kuidas kiirendada äriprotsesside automatiseerimist, et rakendus saaks hakkama varase liiklusega tootmises

Mis on API-platvorm?

Nagu kirjeldab Ed Shelley ChartMogulist, on sellisel teenusel mõned üsna raskesti kasutamata funktsioonid:

  • Puudub kasutajaliides (GUI). Või on mõnel juhul olemas GUI, kuid see on põhitootele teisejärguline.
  • Teenusega suhtlemine toimub veebipõhise API kaudu. See on programmiline viis teenuste ühendamiseks ja andmete edastamiseks kogu veebis masinloetaval viisil.
  • Teenuse väärtus on tavaliselt edastatud andmetes (API kaudu).
  • Hinnakujundus on sageli kasutuspõhine, see tähendab, et kulu põhineb API-le tehtud taotluste arvul.

Põhimõtteliselt on nende pakutav ehitusplokkide komplekt, tavaliselt SaaS-i mudelis. Nende abil saate konkreetse funktsionaalsuse luua vähem koodiga. Selle üks esimesi ja ilmselt märkimisväärsemaid esindajaid on Stripe. Stripe aitab makseid töödelda. Kuid võite olla hiljuti kuulnud teistest suurtest kaladest, kes on turult välja tulnud, näiteks Twilio või Algolia.

Miks kasutada API-platvormi?

Alustame väikese lahtiütlemisega. Selles õpetuses kirjeldatakse, kuidas arendada rakendusi ilma serveripooleta. Kuid usume, et see ei ole pragmaatiline lähenemine tarkvaraarhitektuurile.

Pigem tahame esile tõsta teie tagatehnika mõningaid osi, mida te ei pea nullist juurutama. See kehtib eriti siis, kui konkreetse funktsiooni ärinõuded pole kivisse raiutud ja teie eesmärk on need tegelikult välja mõelda. Teisisõnu, selleks, et teada saada, kas funktsionaalsus saab kasutajatelt positiivse vastuse ja kas teie tootel on lõpuks oma koht.

Samal ajal ei soovi te oma toodet lukustada pakkujaga pakutava müüjaga. Selle põhjuseks on asjaolu, et teate, et see viib varem või hiljem „põrgu lahendama“. Ja nagu olete õppinud, on sealt raske tagasi tulla.

Näitena võite ette kujutada, et teie ettevõte soovib luua ajaveebi. Veelgi enam, nad on juba teatanud, et soovivad seda laiendada ja teenida raha teele. Enne sellise stsenaariumi korral tehnikapinu välja töötamist peate arvestama 2 kaudse nõudega:

  • Soovite ajaveebi funktsionaalsust kiiresti tarnida - äri ei jõua lihtsa ajaveebi jaoks juba ammu oodata.
  • Te ei taha lõpuks žongleerida Wordpressi pistikprogrammidega.

Seda tüüpi vastus võib olla vastus. Need annavad teile mõned funktsionaalsed ehitusplokid ja teie ainus ülesanne on kohandada neid oma ettevõttega.

Teil on hea meel, sest teil on täielik kontroll oma koodibaasi üle. Lisaks on juhtkond ka rahul, sest nad saavad väärtust 1. päevast.Lisaks ei pea nad ettemaksu maksma!

Niisiis, näitame nüüd, kuidas need tööriistad võivad säästa nädalaid inseneriaega, hoides siiski oma koodibaasi muudatuste jaoks avatud.

Märkus . Tööriistad, mida hakkame kasutama, töötavad ka serveripoolses režiimis. Need pakuvad turvaliste API-võtmete abil ühenduse loomisel rohkem funktsionaalsust. Seega arvame, et pragmaatilisem on see integreerida serveri poolele. Sellegipoolest kasutame eksperimendina ainult kliendipoolset funktsionaalsust. Lisaks kasutame erinevate äriprotsesside kiireks automatiseerimiseks mõnda Zapieri liimi.

nostalgia.io

Me kavatseme ehitada turu pärandveebitehnoloogia konsultantidele - nostalgia.io. Kui otsite mingil juhul abi vanast Strutsil või Google Web Toolkitil põhinevast süsteemist, on see koht, kuhu minna. Selle õpetuse esimeses osas õpime, kuidas kasutada mitut API-esimest platvormi järgmise funktsiooni edastamiseks:

  • Pärandtehnoloogiate sirvimine
  • Asjatundjate otsimine ja filtreerimine täisteksti abil
  • Kohtumiste broneerimine ekspertidega
  • Allahindlus kupongidega

Tehnoloogiline virn koosneb järgmistest osadest:

  • Sisukas - tehnoloogiate ja ekspertide andmebaasina
  • Algoolia - täistekstiotsingu jaoks
  • Timekit - saadavuse kontrollimiseks ja broneerimiseks
  • Tüübivorm - vormide jaoks
  • Voucherify - kupongide haldamiseks (lahtiütlus: see on meie toode)

Märkus. Me ei hõlma autentimist ja maksete töötlemist ise. Võite proovida neid ise kodutööna rakendada (vihje: võib-olla on abiks auth0 ja Stripe).

Hüppame koodi juurde.

Märkus 1: lühiduse huvides ei kirjelda me üksikasjalikku üksikasjalikku juhendit. Peaksite tehnilistest andmetest puuduvad osad üles otsima - õnneks on API-esmakordsetel pakkujatel tavaliselt arendajale sobivad dokumendid, põhjalik API viide ja kümneid kasulikke juhendeid.

Märkus 2: Staatilise veebisaidi majutamiseks on palju võimalusi. Kasutame glitchi arendusplatvormi, et saaksite selle hõlpsalt ümber teha ja sellega ise mängida.

Märkus 3: me ei hooli rakenduse välimusest ja olemusest, et mitte varjata integratsiooniosa, pluss see sobib kuidagi äriteemale, kas pole? :)

Andmemudel - sisukas

Tavaliselt algab rakenduse kujundus andmesuhete mudelist. See peaks olema ka meie jaoks esimene mure. Kuid jätame hetkeks andmebaaside pakkujate arutelu vahele ja läheme otse mudelitesse. Kuidas nii?

Meet Contentful - peata CMS. Ägeda lihtsustuse abil saate mõelda sellest kui Wordpressist ilma esiotsa.

See võimaldab:

  • arendajad edastama meediumile kohandatud sisu, olgu see siis veebisait, mobiilirakendus või VR-seade - seda tehakse RESTful API kaudu
  • turundajad saavad luua, hallata ja avaldada sisu, ilma et peaksite vormindamisega tegelema - sisumudeli juhtpaneeli ja rikas tekstiredaktori toel

We’ll use Contentful to create 2 basic entities — Technology and Expert. An Expert knows one or many Technologies. Let’s see how easy it is to create such entities, add some real objects, and display them on a static page.

Technology Browser

With Contentful’s model manager, designing an entity is as easy as drag’n’dropping new fields into the data content model manager. There are 8 different types. These include the default, like a string or number. There as also some specific types, like Location or Media, which come with useful properties.

Create a free account. Then follow the on-boarding guide to create a space.

Finally, create your first model, similar to what you can see in the screenshot below:

Now that you have the Technology model, go to the Content tab to create a couple of instances. As you can see, Contentful provides an intuitive editor for data entry. It takes care of data validation, localization, publishing status, version control, and much more. It’s first and foremost a developer-first platform. Yet these features satisfy marketers and content managers too.

Enough clicking, let’s get to coding. The first task is to display the technologies we’ve just created. To do so, we’ll use Contentful JavaScript SDK.

It makes fetching technologies easy and comes down to 3 steps:

  • Create a new glitch website project, load the contentful.js script, and initialize it with the credentials you can find in the API section.

Note: there are 2 types of keys available in Contentful. One is for content management and one is for content delivery.

The first type can be used to create, update, or delete new models or their instances programmatically.

The second gives you a way to deliver your content to your website or app.

This distinction has been made for security reasons. You don’t want to publish your content management keys on your website, do you? The same applies to the other API-first platforms we’re using in this tutorial.

  • Call getEntries method. This loads the content according to your query parameters. In our case, we want to load only the “Technology” entities. Build some front-end on top of the data . What you get from Contentful is pure JSON (example). Now you can display it to your users as you want. That’s one of the biggest pros when you want or have to adapt your content to multiple devices.

Take a look at this gist:

const client = contentful.createClient({ space: SPACE_ID, accessToken: ACCESS_TOKEN }) const techCards = document.querySelector('#cards'); function fetchTechnologies () { return client.getEntries({ content_type: "technology" }) .then((response) => response.items) .catch((error) => { console.log(`\nError occurred while fetching Entries for Technology:`) console.error(error) }) } fetchTechnologies().then((technologies) => { techCards.innerHTML += technologies.map(technology => ` 

${technology.fields.name}

${technology.fields.description}

`).join('') })

Short and sweet, isn’t it? You can see the overall effect here.

Adding Experts and the Search

So, now we want to display the list of experts when somebody chooses a particular tech. That should be similar to what we’ve just done with Technology a second ago. But let’s make it a bit more advanced. What if we want to make experts searchable? Think of full-text search in their profiles and also a price filter.

Certainly, you can build it on top of Contentful. For example, add another entity, configure search mechanics and UI with getEntries, but there’s a faster way. And by saying faster I mean in both implementation time and the speed of loading search results.

We’ll use another API provider — Algolia. Their platform makes it easy to build and maintain super-fast full-text search. They take care of typo-tolerance, synonyms, geosearch and other little issues. These issues you would most likely bump into when your search feature goes to production.

How does it work? You just use a RESTful API to feed their engine with the data. Then, you configure what attributes should be searchable and how the results should be ranked. Finally, using their JavaScript SDK, you can deliver the instant search experience to any website. Let’s make our experts searchable now!

We’ll start off by creating a data model in Contentful and creating a relationship with Technology entity. Then, we’ll build an Algolia index and add our entities (JSON format) to it.

Add another content model with the fields you can see below:

Notice that we’ve made a one-to-many relationships using the Reference field type. We just want to reflect that any expert might know more than one tech. Once ready, add some experts and assign them to their technologies manually. Use multiple technologies for one of the experts.

You should end up having a similar list:

And the JSON structure looks like:

 { "sys":{ "space":{ "sys":{ "type":"Link", "linkType":"Space", "id":"n763nxcwuf4y" } }, "id":"1mn1mwlwAcQWqgQamsIEmW", "type":"Entry", "createdAt":"2017-12-05T11:29:35.202Z", "updatedAt":"2017-12-13T10:04:52.381Z", "revision":7, "contentType":{ "sys":{ "type":"Link", "linkType":"ContentType", "id":"expert" } }, "locale":"en-US" }, "fields":{ "name":"Javier Hernandez", "technologies":[ { "sys":{ "type":"Link", "linkType":"Entry", "id":"5oKmKwfdjGO2cCaCkwamKW" } }, { "sys":{ "type":"Link", "linkType":"Entry", "id":"7Dtej0GnXqw6cSIMmA6Cko" } } ], "image":{ "sys":{ "type":"Link", "linkType":"Asset", "id":"4RZoQOCwvCMEWMMCuqA0ey" } }, "description":"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Sed faucibus turpis in eu mi bibendum. Mauris in aliquam sem fringilla ut. Tincidunt nunc pulvinar sapien et ligula. ", "projects":53, "price":40, "city":{ "lon":2.2247314453125, "lat":41.36933709640475 } } }

Let’s upload our experts to Algolia. Sign up for a free account, go to the Indices section and run NEW INDEX.

Now we need to transfer our entities from Contentful to Algolia. We could’ve used a dedicated migrator. This is a fantastic tool that automatically loads your content. It then removes, in this case redundant, the Contentful system information (see the gist above) from effective JSONs. It can also resolve relationships. For example instead of IDs, you’ll send the actual names when it comes to the “technologies” field. Finally it syncs with the Algolia index.

But we’ll deliberately do it manually. We need a small improvement in the way we build our index. Therefore, syncing one-to-one with the migrator isn’t an option in our case.

When we use search input in a technology site, naturally we want to include only the experts of chosen technology in the search results. As you can see in the Expert JSON example, technologies are represented as an array of objects. The problem is that you can’t build a facet which filters the data based on a nested array of objects with Algolia.

What they suggest is to split the expert object into as many sub-objects as the number of technologies. So, in the case of Javier Hernandez, who knows 2 frameworks, we should add 2 objects:

{ name: "Javier Hernandez", technologies: { name: “Google Web Toolkit” … // other properties } … // other properties } { name: "Javier Hernandez" technologies: { name: “Apache Struts 1” … // other properties } … // other properties }

As an exercise, you can create a script that splits experts and adds them to the index through the Algolia API. You’ll need Algolia server-side authentication keys. Here’s a snippet which handles the split logic. Notice that the script also purges Contentful’s system info.

This makes the objects lighter will make the search faster:

client.getEntries({ content_type: "expert" }) .then((response) => { const denormalized = [].concat(...response.items.map(item => { let arr = [] item.fields.contentfulID = item.sys.id delete item.sys item.fields.technologies.forEach(tech => { const i = JSON.parse(JSON.stringify(item)) i.fields.technologies = tech.fields i.fields.image = item.fields.image.fields arr.push(i.fields) }) return arr })) console.log(JSON.stringify(denormalized)) }) .catch((error) => { console.log(`\nError occurred while fetching Entries for Expert:`) console.error(error) })

As we have 6 experts and 2 of them know 2 technologies, we should end up with 8 objects in the index. As an alternative to the API insert method, you can upload them with the dashboard. Once uploaded, you can try to use the search in the Dashboard to see how fast Algolia filters the data.

Now, we’re almost ready to connect our search to Algolia. Almost — because we need to create a facet which will allow us to filter results by technology and price. Go to DISPLAY and select technology.name and price in “Attributes for faceting”, then Save.

Finally, we can connect our search to our index so that it retrieves and displays the results. Algolia comes with an advanced JavaScript library which makes it easy as pie.

Take a look at this code:

const isConfig = { appId: 'N675AF3ESI', apiKey: '14b65c352deb9a505131d3d00cba2f6c', indexName: 'experts', urlSync: false } isConfig.searchParameters = { filters: `technologies.name:"${selectedTechnology}"` } const search = instantsearch(isConfig) search.addWidget( instantsearch.widgets.searchBox({ container: '#search-input' }) ) search.addWidget( instantsearch.widgets.hits({ container: '#hits', hitsPerPage: 10, templates: { item: document.getElementById('hit-template').innerHTML, empty: "We didn't find any results for the search \"{{query}}\"" }, cssClasses: { root: 'row', item: 'col-md-4' } }) ) search.addWidget( instantsearch.widgets.rangeSlider({ container: '#price-refinement', attributeName: 'price', tooltips: { format: function(rawValue) { return '$' + Math.round(rawValue).toLocaleString(); } } }) ) search.start()

Notice how we configure the search to use the technology filter in lines 8–10. See how easy it is to adjust the result page to a respective container — line 28 (though it’s hard to find in the docs).

Overall, with about 2-dozen lines and you get this:

So far, we’ve built a simple expert browser supporting full-text search and price sliders. Adding new experts is troublesome at this stage because you have to first manually create them in Contentful and then sync it with Algolia. We’ll automate this in the second part.

The good news is that you can already use this prototype to get some early feedback for the technology browsing and experts filtering. The next step is to create the expert profile page and enable booking.

The search demo code can be found in experts.html.

Bookings

As you might’ve guessed, we won’t be implementing calendar functionality from scratch either. We’ll use Timekit. They offer the API + dashboard to manage calendars and bookings for people and resources. Think of it as a Google/Outlook calendar engine exposed with REST API.

The process of making experts bookable with Timekit is as follows:

  • Create a Resource entity and an assigned Calendar entity
  • Store the resource and calendar IDs in a corresponding expert entity in Contentful
  • Use Timekit JS SDK to display the calendar on an expert’s profile page

And that’s it, you’ve just got bookings up-and-running! Don’t believe me? Read on:

  • Create an account and start a free trial (there’s no free version).
  • Create a Project in which you’ll define the basic calendar mechanics . For instance, event duration, minimum notice, and reminders.
  • Define if the booking requests should be accepted automatically or must be confirmed manually.

For each expert, create a resource and within this resource, create a calendar. Notice that one resource might have more than one calendar.

This is a nice feature to keep in mind when we plan some upgrades in Nostalgia’s business model.

Now, we have to store the resource’s email, newly created calendar ID, and the client-side API key in the corresponding expert entity in Contentful.

You can edit the expert content model and add a JSON field named timekit. Then, modify the expert entities to add timekit details.

The last step is to display the actual calendar in the expert’s profile page. You already know the process. Include an SDK script and configure it properly to render the widget.

But this time we need to load 2 libraries:

  • Contentful — to load customers details, including Timekit credentials
  • Timekit — to place the calendar assigned to a given expert

Here’s the code:

const widget = new TimekitBooking() const client = contentful.createClient({ space: SPACE_ID, accessToken: ACCESS_TOKEN }) client.getEntries({'sys.id': expertId}).then((response) => { const e = response.items[0].fields expertWidget.innerHTML= ` 

${e.name}

$${e.price}

projects: ${e.projects}

${e.description}

` const timekitConf = e.timekit widget.init({ targetEl: '#bookingjs', app: 'nostalgia-4592', apiToken: timekitConf.apiToken, email: timekitConf.email, calendar: timekitConf.calendar, name: 'Jane Doe', timekitFindTime: { length: '3 hours', start: 'tomorrow', filters: { and: [ { specific_time: { start: '8', end: '17' }} ] } }, fullCalendar: { defaultView: 'month' } }) }) .catch((error) => { console.log(`\nError occurred while fetching Entries for Expert:`) console.error(error) })

Notice how we can adjust the booking details such as time slots (line 39). Timekit offers even more customization capabilities, so make sure to read the booking.js spec.

The effect just blows us away. Twenty lines of code and we have our booking widget in place. Timekit oversees the whole process for you. It helps with resolving conflicts and sends email confirmations to experts and customers.

The most important thing is that this approach is highly flexible. It’s all in code. Every single piece of this mechanism can be adjusted through the API.

For example, let’s suppose we want to review a booking request before accepting. It just so happens that Timekit makes it possible with a single flag. Such options are the real power of API-first solutions. Make sure you read the tutorials and docs to learn all the features.

Coupons

Nostalgia isn’t a well-known business yet. We need to find some way to attract early adopters. One of the oldest and most successful methods is discounts. A discount might be applied either after redeeming a coupon or because of the volume of products in the cart. To implement both cases, you might want to use Voucherify.

Why Voucherify? There are a few basic things you should get right when you want to handle coupons properly to save yourself tons of engineering time:

  • Uniqueness of coupon codes — To reduce fraud and get precise tracking of your promotional campaigns
  • Extensible coupon validation mechanism — This is a generic approach which enables adding/removing/expiring multiple coupon codes
  • Easy monitoring of redemption — This will answer marketing and customer service department questions off the bat

You can take care of these 3 things yourself. However, you can get the same result with a couple of lines using Voucherify API endpoints. By doing so, you can immediately forget about coupon misuse, maintaining the “if” ladder validating whether the code is active and valid. You can also forgo providing marketing teams with coupon campaigns results. Nor will you be drilling down the logs to understand why a customer’s redemption failed.

Let’s create a bulk 1000 coupons. These we’ll send to our early adopters. Finally let’s give the customers the possibility to actually use them in our website to enjoy discounted prices.

Sign up for a Voucherify account and go to the campaign manager to create the first batch of coupon codes. Let’s say each coupon carries 25% off.

In the manager, you can specify the discount details and other business limits. For example, specify the expiration date, max total amount, or a specific customer segment eligible for the discount.

When the manager is done, you can start distributing coupons through various channels. Voucherify offers email, sms, push notification, intercom or braze out of the box. But there’s a lot of other ways available thanks to REST API and webhooks.

Before you send them out, you should give customers an option to redeem them. This can be achieved by using the redemption endpoint from the API. Yet, you can also use the pre-built widget from voucherify.js.

Voucherify allows you to either validate or redeem the coupon.

The validation checks if:

  • the coupon comes from your Voucherify account
  • is not expired or disabled
  • it matches all business rules

The redemption does the validation first and subsequentlymarks the coupon as used. In this part, we’ll wire in validation only to show customers a discounted price. In the second article, we’ll send a redemption request when the booking is confirmed.

Include voucherify.js snippet and optionally the corresponding CSS file for a better look and feel. Then, put in the following code:

Voucherify.initialize( "4dde7477-d8d1-4057-8f91-8a9e7137acee", "404c6c0b-4445-4f14-84b1-f4a58f1da2f6" ) Voucherify.render("#voucher-widget", { textPlaceholder: "Your coupon...", onValidated: function(response) { if (response) { const priceTag = document.querySelector('#priceTag') priceTag.innerHTML = Voucherify.utils.calculatePrice(parseInt(priceTag.innerHTML), response) } } })

The library will render a coupon widget which automatically validates the code against the Voucherify API.

You can test it out with the codes we’ve pre-generated with the campaign manager:

* 25% off: nstlg-CCAMIDFf, nstlg-wZK4CoLs, nstlg-V8eV9A3p

* $5 off: uub-nstlg, afl-nstlg, yeq-nstlg

* expired code: VuFF2Wyy

Notice that you can easily customize codes patterns, prefixes and post-fixes can be useful for tracking and reporting.

Now, paste any coupon code into the widget and see the corresponding discount applied:

n the 2nd article, we’ll show you how to monitor the successful and failed coupon redemptions to see if your promo campaign is on track.

Voucherify offers much more than that. Check out the docs and examples to find out how to build advanced promotions and referral programs in days instead of months.

You can find the booking page code here (scheduler.html).

Recap

We planned to build a proof of concept for a new business application — Nostalgia.io. A prototype we can use to pick early users’ brains. Something we can deliver in a decent timeframe yet not a total throwaway.

Hopefully, we’ve convinced you that with developer-first tools like Contentful, Algolia, Timekit, or Voucherify you can achieve it. Even more importantly, you can do it without setting up any back-end layer at all.

It still requires some manual work to keep data in sync among tools. Yet, the flexibility and speed of iteration of these API-first tools at your fingertips definitely makes up for it.

Certainly, these tools aren’t all light and bright. For example, we bumped into these several issues when going through this article:

  • Contentful getEntry()method doesn’t resolve links. We had to use getEntries() instead to get a single expert entity with profile image URL
  • It took us more than a little while to understand how we can display results using column layout (the default is rows)
  • Timekit doesn’t allow for fetching the calendar instance config using an external id. That’s why we need to store calendar tokens in expert entity in Contentful
  • The Voucherify widget doesn’t enable you to try another valid code without refreshing the website

I’m sure there are many more of them. But you can work these little issues around in far less time than you’d spend to build these features from scratch. On top of that, you avoid the serious and time-consuming architectural mistakes the teams at these platforms have made before you.

The source code of the project can be found here. And the demo is live here!

Hardening and scaling

As you can see, some processes are still manual and thus tedious:

  • Adding new experts
  • Making experts searchable
  • Creating calendars for experts

Järgmises osas liimime need teenused Zapieri abil. Zapier on platvorm, mis hõlbustab API-esmaste platvormide ühendamist. Nii vähendame ülalmainitud ärivoogude juhtimiseks vajalikku käsitsi tööd. Näiteks saavad eksperdid ise registreeruda. Lisaks loob platvorm kõik vajalikud üksused programmiliselt.

Lõpuks lükkame prototüübi tootmisse. See on endiselt varajases staadiumis olev rakendus, kuid on jõulisem ja valmis tegelikke kliente teenima. Püsige lainel!

Uuendus : teise osa leiate siit.