redoc icon indicating copy to clipboard operation
redoc copied to clipboard

Generate curl samples for requests

Open RomanHotsiy opened this issue 9 years ago • 27 comments

RomanHotsiy avatar Jan 26 '16 12:01 RomanHotsiy

:+1:

darklynx avatar Jan 29 '16 16:01 darklynx

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.

cayter avatar Aug 30 '16 18:08 cayter

@cayter yes, this is actually a bug. Thanks for reporting. I've opened a separate issue: https://github.com/Rebilly/ReDoc/issues/93

RomanHotsiy avatar Aug 30 '16 19:08 RomanHotsiy

Ahh ok thanks.

cayter avatar Aug 31 '16 02:08 cayter

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.

adamschnaare avatar Jun 02 '17 21:06 adamschnaare

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: https://github.com/Rebilly/generator-openapi-repo/pull/18 but haven't tested it on any third party definitions.

jgabriels avatar Mar 03 '18 17:03 jgabriels

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

ornicar avatar Apr 03 '18 20:04 ornicar

@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.

jgabriels avatar Apr 03 '18 20:04 jgabriels

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

ornicar avatar Apr 04 '18 03:04 ornicar

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

raderio avatar Apr 05 '18 09:04 raderio

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

bottleboy avatar Dec 13 '18 18:12 bottleboy

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

jgabriels avatar Dec 13 '18 19:12 jgabriels

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?

bottleboy avatar Dec 13 '18 20:12 bottleboy

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.

jgabriels avatar Dec 13 '18 22:12 jgabriels

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

raderio avatar Jul 20 '19 18:07 raderio

Any updates?

hawy31 avatar Oct 15 '19 08:10 hawy31

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.

SebastianStehle avatar Oct 15 '19 09:10 SebastianStehle

@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".

darklynx avatar Oct 15 '19 20:10 darklynx

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

Cloudmersive avatar Dec 29 '19 07:12 Cloudmersive

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

lucie-docs avatar Jan 13 '20 09:01 lucie-docs

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

rishabh12j avatar Mar 24 '20 02:03 rishabh12j

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. : /

paxter avatar May 24 '20 07:05 paxter

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.

rohit-gohri avatar Aug 11 '20 06:08 rohit-gohri

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

hungtsou avatar Jun 04 '21 23:06 hungtsou

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)
}

rsby avatar Jul 22 '21 15:07 rsby

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;
};

BoKKeR avatar Jan 19 '22 10:01 BoKKeR

^^ 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)));

braco avatar Mar 16 '22 23:03 braco