Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Generate curl samples for requests #15

Open
RomanHotsiy opened this issue Jan 26, 2016 · 27 comments
Open

Generate curl samples for requests #15

RomanHotsiy opened this issue Jan 26, 2016 · 27 comments

Comments

@RomanHotsiy
Copy link
Member

No description provided.

@RomanHotsiy RomanHotsiy added this to the v1.0 milestone Jan 26, 2016
@darklynx
Copy link

👍

@RomanHotsiy RomanHotsiy removed this from the v1.0 milestone Jun 3, 2016
@cayter
Copy link

cayter commented Aug 30, 2016

Can we actually render Request Sample when there is x-code-samples specified? I have an use case to add my own written SDK code sample.

@RomanHotsiy
Copy link
Member Author

@cayter yes, this is actually a bug. Thanks for reporting.
I've opened a separate issue: #93

@cayter
Copy link

cayter commented Aug 31, 2016

Ahh ok thanks.

@adamschnaare
Copy link

adamschnaare commented Jun 2, 2017

Just wondering if there was any plans to move on this? This feature would be excellent. I'm not too familiar with the code base, but this seems a good workaround solution before coding up a full API console integration.

@jgabriels
Copy link

jgabriels commented Mar 3, 2018

I have a fully working code generator:
https://github.com/Direct-Freight/df-api-docs/blob/master/scripts/generate-code-samples.js
It's called during the build:
https://github.com/Direct-Freight/df-api-docs/blob/master/scripts/build.js
You can see what the final results looks like here:
http://apidocs.directfreight.com/#tag/boards
I created a pull request here: Redocly/create-openapi-repo#18
but haven't tested it on any third party definitions.

@ornicar
Copy link

ornicar commented Apr 3, 2018

That looks amazing, jgabriel. Can't wait to be able to use it!

@jgabriels
Copy link

jgabriels commented Apr 3, 2018

@ornicar:
It's really only a single file:
https://github.com/Direct-Freight/df-api-docs/blob/master/scripts/generate-code-samples.js
You should be able to just download that one file and run it in your project's root directory.
I would love for someone to run it and let me know if it works for their project.

@ornicar
Copy link

ornicar commented Apr 4, 2018

Thanks, I tried to use it but it doesn't seem to like my YAML file. I'll try something tomorrow.

@raderio
Copy link

raderio commented Apr 5, 2018

Is it possible to grab the code from swagger-ui?

@bottleboy
Copy link

How do you generate the x-code-samples code snippets in the yaml/json file? Is there any way to do it automatically?

@jgabriels
Copy link

How do you generate the x-code-samples code snippets in the yaml/json file? Is there any way to do it automatically?

This is what I use:
https://github.com/Direct-Freight/df-api-docs/blob/master/scripts/generate-code-samples.js

It automatically generates code samples for a bunch of different languages.

You can see what it looks like here:
http://apidocs.directfreight.com/#tag/boards

@bottleboy
Copy link

How do you generate the x-code-samples code snippets in the yaml/json file? Is there any way to do it automatically?

This is what I use:
https://github.com/Direct-Freight/df-api-docs/blob/master/scripts/generate-code-samples.js

It automatically generates code samples for a bunch of different languages.

You can see what it looks like here:
http://apidocs.directfreight.com/#tag/boards

Thank you @jgabriels , but I see that swagger-snippet only works with version 2.0 of Open Api and I have a 3.0 file, is that correct?

@jgabriels
Copy link

Thank you @jgabriels , but I see that swagger-snippet only works with version 2.0 of Open Api and I
have a 3.0 file, is that correct?

I believe that may be correct. One workaround might be to use one of the many 3.0 to 2.0 converters to make a 2.0 version of your api and run the code generator on that.

@raderio
Copy link

raderio commented Jul 20, 2019

Any updates on this?
Maybe the implementation can be borrowed from Swagger UI?

@ghost
Copy link

ghost commented Oct 15, 2019

Any updates?

@SebastianStehle
Copy link

I think this feature is overrated. A simple solution would be to add a "Open in Postman" link. I am not sure if this is possible.

@darklynx
Copy link

@SebastianStehle or simply import YAML to Insomnia, BUT it does not replace the mentioned functionality from this issue at all!

People, like me, may not have Postman around them. If you are in console on the server where you should send the request from, it might take you quite a number of actions before you tunnel the request from your PC to the server and use your favorite UI to send requests through it. And last, but not least: nothing beats the simplicity of sending a request using curl regardless whether you are on Linux, BSD, Mac or Windows, just paste the query into console and press "Enter".

@Cloudmersive
Copy link

It cannot be understated how important Curl support is for API documentation

@lucie-docs
Copy link

Any progress on this issue? This feature is essential yet still missing from ReDoc...

@rishabh12j
Copy link

rishabh12j commented Mar 24, 2020

please guide i am looking for the exact same but unable to get any lead is the feature still missing from ReDoc......
@RomanHotsiy @adamaltman can you please guide us if possible please.Thanks in Advance

@paxter
Copy link

paxter commented May 24, 2020

I tried swagger-codegen, openapi-generator and now landed here. It's the best choice in my opinion, but a CURL example support is the one feature I'm missing here. : /

@rohit-gohri
Copy link

https://github.com/cdwv/oas3-api-snippet-enricher works for some cases. It looks for defaults/examples in a particular place so if you have them differently the snippets won't be very helpful.

@hungtsou
Copy link

hungtsou commented Jun 4, 2021

This package worked for me I hope it helps someone.
openapi-snippet

@rsby
Copy link

rsby commented Jul 22, 2021

Using the openapi-snippet mentioned above by hungtsou, the following (rough) script will add the x-code-samples as expected by Redoc:

// USAGE:  node add_api_snippets.js my_api.yml > my_api_with_snippets.yml

const OpenAPISnippet = require('openapi-snippet')
const yaml = require('js-yaml');
const fs = require('fs');

const openApi = yaml.load(fs.readFileSync(process.argv.slice(2)[0], 'utf8'));
const targets = ['node_fetch', 'python_requests', 'shell_curl'];

try {
    Object.keys(openApi.paths).forEach(path => {
        Object.keys(openApi.paths[path]).forEach(method => {
            const snippets = OpenAPISnippet.getEndpointSnippets(openApi, path, method, targets);
            const samples = []
            openApi.paths[path][method]['x-code-samples'] = samples;
            snippets.snippets.forEach(snippet => {
                samples.push({
                    lang: snippet.title.split(' ')[0],
                    source: snippet.content
                })
            })
        })
    })
    console.log(yaml.dump(openApi))
} catch (err) {
    console.log(err)
}

@BoKKeR
Copy link

BoKKeR commented Jan 19, 2022

Here is an improved version of the script above, change x-codeSamples to x-code-samples if you are running old redoc:

const OpenAPISnippet = require('openapi-snippet')

const addRequestSamples = (swaggerJson) => {
  const swagger = JSON.parse(JSON.stringify(swaggerJson));
  const targets = ['shell_curl'];
  const httpRequestMethods = ['get', 'head', 'post', 'put', 'delete', 'options', 'trace', 'patch'];

  for (const singlePath in swagger.paths) {
    Object.keys(swagger.paths[singlePath])
      .filter((method) => httpRequestMethods.some((supportedMethod) => supportedMethod === method))
      .forEach((method) => {
        try {
          const snippets = OpenAPISnippet.getEndpointSnippets(swagger, singlePath, method, targets);
          const samples = [];

          snippets.snippets.forEach((snippet) => {
            samples.push({
              lang: snippet.title.split(' ')[0],
              source: snippet.content,
            });
          });
          swagger.paths[singlePath][method]['x-codeSamples'] = samples;
        } catch (error) {
          console.log(error);
        }
      });
  }

  return swagger;
};

@braco
Copy link

braco commented Mar 16, 2022

^^ the above answers combined

const openAPISnippet = require('openapi-snippet');
const yaml = require('js-yaml');
const fs = require('fs');

const targets = ['node_fetch', 'python_requests', 'shell_curl'];
const httpRequestMethods = ['get', 'head', 'post', 'put', 'delete', 'options', 'trace', 'patch'];

const addRequestSamples = (swaggerJson) => {
  const swagger = JSON.parse(JSON.stringify(swaggerJson));

  for (const singlePath in swagger.paths) {
    Object.keys(swagger.paths[singlePath])
      .filter((method) => httpRequestMethods.some((supportedMethod) => supportedMethod === method))
      .forEach((method) => {
        try {
          const snippets = openAPISnippet.getEndpointSnippets(
            swagger,
            singlePath,
            method,
            targets,
          );
          const samples = [];

          snippets.snippets.forEach((snippet) => {
            samples.push({
              lang: snippet.title.split(' ')[0],
              source: snippet.content,
            });
          });
          swagger.paths[singlePath][method]['x-codeSamples'] = samples;
        } catch (error) {
          console.log(error);
        }
      });
  }

  return swagger;
};

const args = process.argv.slice(2);
const openApi = yaml.load(fs.readFileSync(args[0], 'utf8'));

console.log(yaml.dump(addRequestSamples(openApi)));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests