Redocly / redoc

📘 OpenAPI/Swagger-generated API Reference Documentation
https://redocly.github.io/redoc/
MIT License
22.88k stars 2.26k forks source link

Generate curl samples for requests #15

Open RomanHotsiy opened 8 years ago

darklynx commented 8 years ago

:+1:

cayter commented 7 years ago

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 commented 7 years ago

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

cayter commented 7 years ago

Ahh ok thanks.

adamschnaare commented 7 years ago

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 commented 6 years ago

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.

ornicar commented 6 years ago

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

jgabriels commented 6 years ago

@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 commented 6 years ago

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

raderio commented 6 years ago

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

bottleboy commented 5 years ago

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

jgabriels commented 5 years ago

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 commented 5 years ago

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 commented 5 years ago

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 commented 4 years ago

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

ghost commented 4 years ago

Any updates?

SebastianStehle commented 4 years ago

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 commented 4 years ago

@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 commented 4 years ago

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

lucie-docs commented 4 years ago

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

rishabh12j commented 4 years ago

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 commented 4 years ago

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 commented 3 years ago

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 commented 3 years ago

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

rsby commented 2 years ago

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 commented 2 years ago

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 commented 2 years ago

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