Real live example of OpenAPI in a front-end project

By Maarten Van Hoof

2 min read

Authors

In the previous parts of this series, we introduced you to the OpenAPI specification, how to describe an API provider in an OpenAPI document, the approaches we can take incorporating it on workflows helping us build and integrate with RESTful APIs, and the tooling that is available to optimise our OpenAPI workflows. In this final part of the series, we will show you how we can use OpenAPI in a front-end monorepo project.

I've created a demo repository showing the power of OpenAPI and automation in a front-end project.

vanhoofmaarten/openapi-monorepo-demo (github.com)

Project structure

The project is set up as a monorepo. Each domain lives as a separate entity in the packages folder, but because they are very much interdependent, they are within the same repository.

.
β”œβ”€β”€ packages/
β”‚   β”œβ”€β”€ frontend/
β”‚   β”‚   β”œβ”€β”€ index.html
β”‚   β”‚   β”œβ”€β”€ main.ts
β”‚   β”‚   └── ...
β”‚   β”œβ”€β”€ mock/
β”‚   β”‚   └── ...
β”‚   β”œβ”€β”€ openapi/
β”‚   β”‚   β”œβ”€β”€ petstore.yml
β”‚   β”‚   └── ...
β”‚   └── sdk/
β”‚       β”œβ”€β”€ (generated API client)
β”‚       └── ...
β”œβ”€β”€ package.json
└── ...

OpenAPI document

The OpenAPI document is fetched from a different repository using Git submodules. It contains its own linting rules and own automation. We include it in our project to refer to the OpenAPI document itself.

SDK

The sdk folder only contains the configuration and scripts for generating a TypeScript-based API client by openapi-typescript-codegen. Git ignores generated files.

"scripts": {
  "dev": "npm run generate",
  "generate": "openapi --input ../openapi/petstore.yml --output ./src && tsc"
},

Mocks

The mocks folder contains the configuration and scripts to run the Prism mocking server.

"scripts": {
  "dev": "prism mock -d ../openapi/petstore.yml"
}

Front-end

The front-end folder contains a Vite application dependent on the SDK folder. In the main.ts file, we import the PetsService, set the SDK base URL, and fetch data with the listPets method. The retrieved data will be outputted in the HTML element with the id preview.

// Import the generated API client
import { OpenAPI, PetsService } from '../sdk/dist'

// Set the base URL of the API client
OpenAPI.BASE = 'http://localhost:4010'

// Fetch data
const data = await PetsService.listPets(3243)

// Output the data in the HTML
const preview = document.getElementById('preview')

if (preview) {
  preview.innerHTML = JSON.stringify(data, null, 2)
}

Orchestration

With the help of Lerna, a tool to orchestrate monorepo tasks, when running npm run dev, our entire development will start with just one command. First, it will generate the SDK. Then it will start the Vite dev environment and the mocking server in parallel.

➜ npm run dev

> dev
> lerna run --parallel --scope @mrtnvh/*-sdk dev && lerna run --parallel --scope @mrtnvh/*-frontend --scope @mrtnvh/*-mock dev

lerna notice cli v5.1.6
lerna notice filter including "@mrtnvh/*-sdk"
lerna info filter [ '@mrtnvh/*-sdk' ]
lerna info Executing command in 1 package: "npm run dev"
@mrtnvh/frontend-loves-openapi-demo-sdk: > @mrtnvh/frontend-loves-openapi-demo-sdk@0.0.0 dev
@mrtnvh/frontend-loves-openapi-demo-sdk: > npm run generate
@mrtnvh/frontend-loves-openapi-demo-sdk: > @mrtnvh/frontend-loves-openapi-demo-sdk@0.0.0 generate
@mrtnvh/frontend-loves-openapi-demo-sdk: > openapi --input ../openapi/petstore.yml --output ./src && tsc
lerna success run Ran npm script 'dev' in 1 package in 2.0s:
lerna success - @mrtnvh/frontend-loves-openapi-demo-sdk

lerna notice cli v5.1.6
lerna notice filter including ["@mrtnvh/*-frontend","@mrtnvh/*-mock"]
lerna info filter [ '@mrtnvh/*-frontend', '@mrtnvh/*-mock' ]
lerna info Executing command in 2 packages: "npm run dev"
@mrtnvh/frontend-loves-openapi-demo-frontend: > @mrtnvh/frontend-loves-openapi-demo-frontend@0.0.0 dev
@mrtnvh/frontend-loves-openapi-demo-frontend: > vite

@mrtnvh/frontend-loves-openapi-demo-mock: > @mrtnvh/frontend-loves-openapi-demo-mock@0.0.0 dev
@mrtnvh/frontend-loves-openapi-demo-mock: > prism mock -d ../openapi/petstore.yml

@mrtnvh/frontend-loves-openapi-demo-frontend:   vite v2.9.13 dev server running at:
@mrtnvh/frontend-loves-openapi-demo-frontend:   > Local: http://localhost:3000/
@mrtnvh/frontend-loves-openapi-demo-frontend:   > Network: use `--host` to expose
@mrtnvh/frontend-loves-openapi-demo-frontend:   ready in 81ms.

@mrtnvh/frontend-loves-openapi-demo-mock: [2:51:01 PM] β€Ί [CLI] …  awaiting  Starting Prism…
@mrtnvh/frontend-loves-openapi-demo-mock: [2:51:01 PM] β€Ί [CLI] β„Ή  info      GET        http://127.0.0.1:4010/Pets
@mrtnvh/frontend-loves-openapi-demo-mock: [2:51:01 PM] β€Ί [CLI] β„Ή  info      POST       http://127.0.0.1:4010/Pets
@mrtnvh/frontend-loves-openapi-demo-mock: [2:51:01 PM] β€Ί [CLI] β„Ή  info      GET        http://127.0.0.1:4010/pets/similique
@mrtnvh/frontend-loves-openapi-demo-mock: [2:51:01 PM] β€Ί [CLI] β–Ά  start     Prism is listening on http://127.0.0.1:4010

When we visit the front-end development server on the provided address, typically at http://localhost:3000, we see our list of mocked data, verifying that our solution works.

Wrap-up

Using this project structure as default in all our projects has helped us reduce project setup time significantly. We can now focus on the end-user, building features that will improve the final product, rather then having to spend time on bootstrapping it.

If you'd made it here so far, thank you for reading! I hope you enjoyed this and that OpenAPI help you improve your API development workflow.


Upcoming events

  • Coven of Wisdom - Herentals - Winter `24 edition

    Worstelen jij en je team met automated testing en performance? Kom naar onze meetup waar ervaren sprekers hun inzichten en ervaringen delen over het bouwen van robuuste en efficiΓ«nte applicaties. Schrijf je in voor een avond vol kennis, heerlijk eten en een mix van creativiteit en technologie! πŸš€ 18:00 – πŸšͺ Deuren open 18:15 – πŸ• Food & drinks 19:00 – πŸ“’ Talk 1 20:00 – 🍹 Kleine pauze 20:15 – πŸ“’ Talk 2 21:00 – πŸ™‹β€β™€οΈ Drinks 22:00 – 🍻 Tot de volgende keer? Tijdens deze meetup gaan we dieper in op automated testing en performance. Onze sprekers delen heel wat praktische inzichten en ervaringen. Ze vertellen je hoe je effectieve geautomatiseerde tests kunt schrijven en onderhouden, en hoe je de prestaties van je applicatie kunt optimaliseren. Houd onze updates in de gaten voor meer informatie over de sprekers en hun specifieke onderwerpen. Over iO Wij zijn iO: een groeiend team van experts die end-to-end-diensten aanbieden voor communicatie en digitale transformatie. We denken groot en werken lokaal. Aan strategie, creatie, content, marketing en technologie. In nauwe samenwerking met onze klanten om hun merken te versterken, hun digitale systemen te verbeteren en hun toekomstbestendige groei veilig te stellen. We helpen klanten niet alleen hun zakelijke doelen te bereiken. Samen verkennen en benutten we de eindeloze mogelijkheden die markten in constante verandering bieden. De springplank voor die visie is talent. Onze campus is onze broedplaats voor innovatie, die een omgeving creΓ«ert die talent de ruimte en stimulans geeft die het nodig heeft om te ontkiemen, te ontwikkelen en te floreren. Want werken aan de infinite opportunities van morgen, dat doen we vandaag.

    | Coven of Wisdom Herentals

    Go to page for Coven of Wisdom - Herentals - Winter `24 edition
  • Mastering Event-Driven Design

    PLEASE RSVP SO THAT WE KNOW HOW MUCH FOOD WE WILL NEED Are you and your team struggling with event-driven microservices? Join us for a meetup with Mehmet Akif TΓΌtΓΌncΓΌ, a senior software engineer, who has given multiple great talks so far and Allard Buijze founder of CTO and founder of AxonIQ, who built the fundaments of the Axon Framework. RSVP for an evening of learning, delicious food, and the fusion of creativity and tech! πŸš€ 18:00 – πŸšͺ Doors open to the public 18:15 – πŸ• Let’s eat 19:00 – πŸ“’ Getting Your Axe On Event Sourcing with Axon Framework 20:00 – 🍹 Small break 20:15 – πŸ“’ Event-Driven Microservices - Beyond the Fairy Tale 21:00 – πŸ™‹β€β™€οΈ drinks 22:00 – 🍻 See you next time? Details: Getting Your Axe On - Event Sourcing with Axon Framework In this presentation, we will explore the basics of event-driven architecture using Axon Framework. We'll start by explaining key concepts such as Event Sourcing and Command Query Responsibility Segregation (CQRS), and how they can improve the scalability and maintainability of modern applications. You will learn what Axon Framework is, how it simplifies implementing these patterns, and see hands-on examples of setting up a project with Axon Framework and Spring Boot. Whether you are new to these concepts or looking to understand them more, this session will provide practical insights and tools to help you build resilient and efficient applications. Event-Driven Microservices - Beyond the Fairy Tale Our applications need to be faster, better, bigger, smarter, and more enjoyable to meet our demanding end-users needs. In recent years, the way we build, run, and operate our software has changed significantly. We use scalable platforms to deploy and manage our applications. Instead of big monolithic deployment applications, we now deploy small, functionally consistent components as microservices. Problem. Solved. Right? Unfortunately, for most of us, microservices, and especially their event-driven variants, do not deliver on the beautiful, fairy-tale-like promises that surround them.In this session, Allard will share a different take on microservices. We will see that not much has changed in how we build software, which is why so many β€œmicroservices projects” fail nowadays. What lessons can we learn from concepts like DDD, CQRS, and Event Sourcing to help manage the complexity of our systems? He will also show how message-driven communication allows us to focus on finding the boundaries of functionally cohesive components, which we can evolve into microservices should the need arise.

    | Coven of Wisdom - Utrecht

    Go to page for Mastering Event-Driven Design
  • The Leadership Meetup

    PLEASE RSVP SO THAT WE KNOW HOW MUCH FOOD WE WILL NEED What distinguishes a software developer from a software team lead? As a team leader, you are responsible for people, their performance, and motivation. Your output is the output of your team. Whether you are a front-end or back-end developer, or any other discipline that wants to grow into the role of a tech lead, RSVP for an evening of learning, delicious food, and the fusion of leadership and tech! πŸš€ 18:00 – πŸšͺ Doors open to the public 18:15 – πŸ• Let’s eat 19:00 – πŸ“’ First round of Talks 19:45 – 🍹 Small break 20:00 – πŸ“’ Second round of Talks 20:45 – πŸ™‹β€β™€οΈ drinks 21:00 – 🍻 See you next time? First Round of Talks: Pixel Perfect and Perfectly Insane: About That Time My Brain Just Switched Off Remy Parzinski, Design System Lead at Logius Learn from Remy how you can care for yourself because we all need to. Second Round of Talks: Becoming a LeadDev at your client; How to Fail at Large (or How to Do Slightly Better) Arno Koehler Engineering Manager @ iO What are the things that will help you become a lead engineer? Building Team Culture (Tales of trust and positivity) Michel Blankenstein Engineering Manager @ iO & Head of Technology @ Zorggenoot How do you create a culture at your company or team? RSVP now to secure your spot, and let's explore the fascinating world of design systems together!

    | Coven of Wisdom - Amsterdam

    Go to page for The Leadership Meetup

Share