Skip to content

feat: experimental /_nitro/openapi.json and /_nitro/swagger endpoints for dev mode - #1162

Merged
pi0 merged 2 commits into
mainfrom
feat/openapi
Apr 21, 2023
Merged

pi0 merged 2 commits into
mainfrom
feat/openapi

Conversation

@pi0

@pi0 pi0 commented Apr 17, 2023 •

Copy link
Copy Markdown
Member

🔗 Linked issue

Resolves #3
Resolved #4

❓ Type of change

  • 📖 Documentation (updates to the documentation or readme)
  • 🐞 Bug fix (a non-breaking change that fixes an issue)
  • 👌 Enhancement (improving an existing functionality like performance)
  • ✨ New feature (a non-breaking change that adds functionality)
  • ⚠️ Breaking change (fix or feature that would cause existing functionality to change)

📚 Description

This PR exposes available routes and an initial meta using Open API 3 standard.

It exposes two endpoints for development:

  • /_nitro/openapi.json: JSON response that can be integrated with external tools and setups such as Postman and Nuxt devtools to access available routes meta (/cc @antfu)
  • /_nitro/swagger: A basic UI that makes local debugging easier

This feature opens the next steps in supporting generic and extendable route meta via a well-defined standard.

image

📝 Checklist

  • I have linked an issue or discussion.
  • I have updated the documentation accordingly.

@pi0 pi0 changed the title feat: expose open api and swagger ui for development mode feat: expose openapi and swagger ui for dev mode Apr 17, 2023
@codecov

codecov Bot commented Apr 17, 2023 •

Copy link
Copy Markdown

Codecov Report

Merging #1162 (4071a14) into main (1d218eb) will decrease coverage by 9.10%.
The diff coverage is 100.00%.

❗ Current head 4071a14 differs from pull request most recent head 959f2b1. Consider uploading reports for the commit 959f2b1 to get more accurate results

@@            Coverage Diff             @@
##             main    #1162      +/-   ##
==========================================
- Coverage   77.09%   67.99%   -9.10%     
==========================================
  Files          67       66       -1     
  Lines        6613     6512     -101     
  Branches      727      728       +1     
==========================================
- Hits         5098     4428     -670     
- Misses       1514     2069     +555     
- Partials        1       15      +14     
Impacted Files Coverage Δ
src/options.ts 87.82% <100.00%> (-7.99%) ⬇️
src/rollup/plugins/handlers.ts 94.32% <100.00%> (-0.17%) ⬇️

... and 29 files with indirect coverage changes

Help us with your feedback. Take ten seconds to tell us how you rate us. Have a feature suggestion? Share it here.

@antfu

antfu commented Apr 17, 2023

Copy link
Copy Markdown
Member

That would be great! 🔥

@pi0
pi0 marked this pull request as ready for review April 21, 2023 10:35
@pi0 pi0 changed the title feat: expose openapi and swagger ui for dev mode feat: experimental /_nitro/openapi.json and /_nitro/swagger endpoints for dev mode Apr 21, 2023
@pi0
pi0 merged commit 720fe29 into main Apr 21, 2023
@pi0
pi0 deleted the feat/openapi branch April 21, 2023 10:36
@septatrix

Copy link
Copy Markdown
Contributor

Hot damn, I forgot I even commented on that issue but it has just become relevant again for a project. Will definitely check it out ASAP (which might sadly not be too soon as I'm quite busy :/)!

// Served as /_nitro/swagger
export default eventHandler((event) => {
const title = "Nitro Swagger UI";
const CDN_BASE = "https://cdn.jsdelivr.net/npm/swagger-ui-dist@^4";

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It would be great if this were configurable or bundled for offline usage - though I guess that could be archived by manually recreating this route?

@memic84

memic84 commented May 16, 2023

Copy link
Copy Markdown

Great feature!

It seems that the port 3000 in swagger is hardcoded, and the the port used in Nuxt. I am using port 3001 for this application, and the try out calls, won't work that way.

Is this a bug, or just wrong configuration of nitro on my part?

@septatrix

septatrix commented May 16, 2023 •

Copy link
Copy Markdown
Contributor

I guess https://github.com/unjs/nitro/blob/4111798a09fde7bf5916500637e27d6acc0189d1/src/runtime/routes/openapi.ts#L20 should reuse the host+port(+path+protocol) where the application is exposed

@GionRubitschung

Copy link
Copy Markdown

I have found some problems using this.

Generating the json works, although with some errors. When opening the swagger page I get a json syntax error. I believe this comes from swagger itself. When copying the generated schema into the online swagger editor it has errors. The versioning and parameters are missing an option.

https://github.com/unjs/nitro/blob/2ad43894a6039207fd535d7fdc30ba92d4847ee6/src/runtime/routes/openapi.ts#L16
In the code the version is given as null but the openapi specs are given this as required

Regarding the parameters openapi states this:

A parameter MUST contain either a schema property, or a content property, but not both.

See here

When generating the paths, these properties are not set
https://github.com/unjs/nitro/blob/2ad43894a6039207fd535d7fdc30ba92d4847ee6/src/runtime/routes/openapi.ts#L42

It would be great if there would an option we can define openapi properties for ourself. Maybe directly in the routes via a openapi config object that gets automatically picked up by the feature?

@xieze

xieze commented Jul 23, 2023

Copy link
Copy Markdown

I still don't understand how to use it, can you give me a sample code?

@dnnaji

dnnaji commented Aug 23, 2023

Copy link
Copy Markdown

Just update your Nitro config:

// https://nitro.unjs.io/config
export default defineNitroConfig({
  experimental: {
    openAPI: false,
  },
})

@PrimeTimeTran

Copy link
Copy Markdown

Hey there.

How do we define the params for routes?

I tried following the openapi specification and it doesn't update the UI or JSON.

import _ from 'lodash'
/**
 * @swagger
 * /api/accounts:
 *   get:
 *     summary: Retrieve a list of accounts
 *     description: Get all users from the system
 *     responses:
 *       '200':
 *         description: A list of accounts
 *         content:
 *           application/json:
 *             schema:
 *               type: array
 *               items:
 *                 type: object
 *                 properties:
 *                   id:
 *                     type: integer
 *                   username:
 *                     type: string
 *                   balance:
 *                     type: string
 */
export default defineEventHandler(async (e) => {
  try {
    let { limit, page } = e.context
    let params = getQuery(e)
    const query = buildQuery(params)
    const fieldsToPopulate = [
      { from: 'users', localField: 'user' },
      { from: 'banks', localField: 'bank' },
      { from: 'branches', localField: 'branch' },
      { from: 'transactions', localField: 'transactions' },
    ]
    const pipeline = buildPipeline(query, page, limit, fieldsToPopulate)
    const results = await Account.aggregate(pipeline)
    let { data, totalCount, pageCount } = results[0]
    if (!_.isEmpty(totalCount)) {
      totalCount = totalCount[0].total
    }
    const response = {
      meta: {
        page,
        pageCount,
        totalCount,
      },
      data,
    }
    return response
  } catch (error) {
    console.log({
      error,
    })
  }
})

These routes don't get updated that that codedoc/comment.

http://localhost:3005/_nitro/swagger
http://localhost:3005/_nitro/openapi.json
Screenshot 2023-12-18 at 2 35 25 PM Screenshot 2023-12-18 at 2 35 12 PM

Apologize if that's a WIP and is expected to not work yet. I read through the commit but wasn't sure as I'm not an expert on the openapi spec.

TIA~!

@PrimeTimeTran

Copy link
Copy Markdown

Also are there plans to enable configuring which openapi.json file to use?

If I understand correctly, it's generated via Nitro.
If thats the case then my previous comment is brought up. Regardless, I feel it makes the code too verbose.

I checked the discussions tab and only found this.

My use case is I generating/build routes programmatically and would prefer to generate/build the openapi.json as well and then have nitro point toward that if possible.

@septatrix

Copy link
Copy Markdown
Contributor

How do we define the params for routes?
Apologize if that's a WIP and is expected to not work yet.

It is still an experimental feature and to my knowledge there is no easy mechanism to hook into the generation, yet.

Also are there plans to enable configuring which openapi.json file to use?

If you do not want to use the autogenerated one you could just serve a static file and register the UI endpoint manually.

My use case is I generating/build routes programmatically and would prefer to generate/build the openapi.json as well and then have nitro point toward that if possible.

I assume that once #938 gets merged these features could be combined to infer the types of the OpenAPI spec automatically.

@PrimeTimeTran

PrimeTimeTran commented Dec 18, 2023 •

Copy link
Copy Markdown

If you do not want to use the autogenerated one you could just serve a static file and register the UI endpoint manually.

I tried defining ./server/routes/_nitro/openapi.json and I saw it was found at the bottom of the UI of the swagger page , /_nitro/swagger, but it wasn't used as the src/reference as the doc for the /_nitro/swagger endpoint UI's list/documentation.

My thought here is that although the module can't yet auto generate route params it can be used to build the doc serving UI/endpoint.

I tinkered with it a bit and kept getting complaints from Nuxt regardless of if I used a plugin or module(also extremely new to Nuxt). The configuring of running the swagger ui service/api isn't straight forward imo for those of us who haven't had the chance to custom build a module yet =).

@numselli

Copy link
Copy Markdown

In the v2.4.0 release notes it states We are working to bring route-level meta definition for an even better and more detailed docs generator. I was wondering what the status of that is?

@daviddomkar

Copy link
Copy Markdown

I would also like to be updated on the status of adding the route level meta definitions.

@csmikle

csmikle commented Jun 26, 2024

Copy link
Copy Markdown

I don't know if this is a good place to report this but, I am using this feature in a Nuxt project and it works as long as I'm using npm. When I run an identical project in Bun, I get the "Unable to render this definition. The provided definition does not specify a valid version field." Though openapi.json is requested and looks the same.

@Ismael-Rakotondrazaka

This comment was marked as off-topic.

@ssw1992

ssw1992 commented Aug 11, 2024

Copy link
Copy Markdown

I'm nearly driven to despair by @scalar/scalar, a persistent hardcoded bug that's remained unresolved for months. If this resolves it, I'll be immensely pleased.

This branch was successfully deployed

1 active deployment
Preview — 959f2b1d Deployed Apr 21, 2023 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

swagger API Inspector