Skip to content

Commit 5faaa11

Browse files
erunionkanadgupta
andauthored
docs: v5 (#553)
* docs: v5 * Update bin/build-markdown.js * Update docs/authentication.md Co-authored-by: Kanad Gupta <[email protected]> * Update docs/faq.md Co-authored-by: Kanad Gupta <[email protected]> * Update packages/api/README.md Co-authored-by: Kanad Gupta <[email protected]> * Update docs/upgrading-from-v4.md Co-authored-by: Kanad Gupta <[email protected]> * Update docs/making-requests.md Co-authored-by: Kanad Gupta <[email protected]> * Update docs/upgrading-from-v4.md Co-authored-by: Kanad Gupta <[email protected]> * Update docs/making-requests.md Co-authored-by: Kanad Gupta <[email protected]> * Update docs/making-requests.md Co-authored-by: Kanad Gupta <[email protected]> * Update docs/making-requests.md Co-authored-by: Kanad Gupta <[email protected]> * Update docs/making-requests.md Co-authored-by: Kanad Gupta <[email protected]> * Update docs/making-requests.md Co-authored-by: Kanad Gupta <[email protected]> Co-authored-by: Kanad Gupta <[email protected]>
1 parent 5b6a86a commit 5faaa11

File tree

14 files changed

+161
-63
lines changed

14 files changed

+161
-63
lines changed

.github/CONTRIBUTING.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -53,8 +53,8 @@ const sdk = require('api')(
5353
);
5454

5555
sdk
56-
.get('/anything', { foo: ['bar', 'baz'], baz: 'abc', key: 'value' })
57-
.then(res => console.log(res))
56+
.getAnything({ foo: ['bar', 'baz'], baz: 'abc', key: 'value' })
57+
.then(({ data }) => console.log(data))
5858
.catch(err => console.error(err));
5959
```
6060

bin/build-markdown.js

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -4,22 +4,18 @@ const path = require('path');
44
// eslint-disable-next-line import/no-extraneous-dependencies
55
const { transcludeFile } = require('hercule/promises');
66

7-
/**
8-
* all Markdown files located at within the `docs` directory
9-
* @type {Array.<String>}
10-
*/
7+
// All Markdown files are located within the `docs` directory.
118
const files = fs
129
.readdirSync('docs', { withFileTypes: true })
1310
.filter(fileHandle => fileHandle.isFile())
1411
.map(fileHandle => path.join('docs', fileHandle.name))
1512
.filter(file => file.endsWith('.md') || file.endsWith('.markdown'));
1613

17-
// Clears out and recreates `dist` folder
14+
// Clears out and recreates `dist` folder.
1815
fs.rmSync('dist', { force: true, recursive: true });
1916
fs.mkdirSync('dist/docs', { recursive: true });
2017

21-
// Populates any partials using hercule and then
22-
// writes output to `dist` folder
18+
// Populates any partials using hercule and then writes output to `dist` folder.
2319
files.forEach(fileName => {
2420
transcludeFile(fileName).then(({ output }) => {
2521
fs.writeFileSync(`dist/${fileName}`, output, 'utf-8');

docs/authentication.md

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,13 +6,15 @@ category: 62cc6ce22b8b6601da6cb12d
66
`api` supports API authentication through an `.auth()` method:
77

88
```js
9-
sdk.auth('myApiToken');
10-
sdk.listPets().then(res => {
11-
// response
9+
const petstore = require('@api/petstore');
10+
11+
petstore.auth('myApiToken');
12+
petstore.listPets().then(({ data }) => {
13+
// authenticated response
1214
});
1315
```
1416

15-
With the exception of OpenID, it supports all forms of authentication supported by the OpenAPI specification! Supply `.auth()` with your auth credentials and it'll magically figure out how to use it according to the API you're using. 🧙‍♀️
17+
With the exception of OpenID and Mutual TLS it supports all forms of authentication supported by the OpenAPI specification! Supply `.auth()` with your auth credentials and it'll magically figure out how to use it according to the API you're using. 🧙‍♀️
1618

1719
For example:
1820

@@ -22,4 +24,4 @@ For example:
2224

2325
> 📘
2426
>
25-
> Note that `sdk.auth()` is not chainable.
27+
> The `.auth()` method is not chainable.

docs/faq.md

Lines changed: 15 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,14 @@ Yes! YAML definitions will be automatically converted to JSON when they're fetch
1111

1212
At the moment it does not. If you wish to use an API that has a Swagger 2.0 file, you'll need to first convert it to an OpenAPI 3 definition.
1313

14+
### Does this support OpenAPI 3.1 definitions?
15+
16+
Yes!
17+
18+
### Does this support OpenAPI 4 (Moonwalk) definitions?
19+
20+
No! Since v4 is still in the early planning stages we don't support it but once it's finalized we will.
21+
1422
### Does this support traditional OAuth 2 flows of creating tokens?
1523

1624
Not yet, unfortunately. For APIs that use OAuth 2, you'll need a fully-qualified token already for `api` to make requests.
@@ -19,19 +27,21 @@ Not yet, unfortunately. For APIs that use OAuth 2, you'll need a fully-qualified
1927

2028
Not yet! This is something we're thinking about how to handle, but it's difficult with the simplified nature of the `.auth()` method as it by design does not ask the user to inform the SDK of what kind of authentication scheme the token they're supplying it should match up against.
2129

30+
If you have ideas on how to handle this [we'd love to hear them](https://github.com/readmeio/api/discussions/547).
31+
2232
### Will this work in browsers?
2333

24-
If you generate an SDK with the CLI installation process, then yes! If you're having troubles getting autogenerated SDKs working in a browser, [please let us know](https://github.com/readmeio/api/issues)!
34+
If you generate an SDK with the CLI installation process then yes! If you're having trouble getting autogenerated SDKs working in a browser, [please let us know](https://github.com/readmeio/api/issues)!
2535

26-
Unfortunately the dynamic version of `api` will **not** work in browsers as it requires access to some filesystem handling for managing its cache state.
36+
Unfortunately the dynamic version of `api` will **not** work in browsers as it requires access to the filesystem for handling and managing its cache state.
2737

2838
### Will this validate my data before it reaches the API?
2939

30-
Not yet! This is something we've got planned down the road.
40+
Not yet! This is something we're thinking about in the future.
3141

32-
### Does this support OpenAPI definitions that require authentication to download?
42+
### Does this support fetching OpenAPI definitions that require authentication to download?
3343

34-
Not yet! The URL that you give the module must be publicy accessible. If it isn't, you can download it to your computer/server and then use the absolute path to that file instead.
44+
Not yet! The URL that you give the module must be publicly accessible. If it isn't, you can download it to your computer or server and then use the absolute path to that file instead.
3545

3646
```sh
3747
$ npx api install ./path/to/downloaded.json
@@ -41,14 +51,6 @@ $ npx api install ./path/to/downloaded.json
4151
const sdk = require('api')('./path/to/downloaded.json');
4252
```
4353

44-
### How do I access the Response object (for status and headers)?
45-
46-
By default we parse the response based on the `content-type` header for you. You can disable this by doing the following:
47-
48-
```js
49-
sdk.config({ parseResponse: false });
50-
```
51-
5254
### Where is the cache stored?
5355

5456
See [How does it work?](https://api.readme.dev/docs/how-it-works) for some information on how, when, and where `api` caches its data.

docs/how-it-works.md

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -93,7 +93,7 @@ The `hash` within this is an `md5` of the full OpenAPI definition that we retrie
9393

9494
If for some reason this file gets lost, or the accessor you're supplying to `api` changes for whatever reason `api` will re-retrieve the OpenAPI definition at run-time.
9595

96-
```
96+
```json
9797
{
9898
"d6b93e95fa1a7efdce6d1406dc599923": {
9999
"hash": "cbb821db3609f8983ce1a372dadd122c",
@@ -113,7 +113,7 @@ const sdk = require('api')('https://raw.githubusercontent.com/readmeio/oas-examp
113113
cacheDir: './path/to/my/custom/cache/dir',
114114
});
115115

116-
sdk.listPets().then(res => {
117-
console.log(`My pets name is ${res[0].name}!`);
116+
sdk.listPets().then(({ data })) => {
117+
console.log(`My pets name is ${data[0].name}!`);
118118
});
119119
```

docs/http-requests.md

Lines changed: 0 additions & 12 deletions
This file was deleted.

docs/making-requests.md

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
---
2+
title: Making Requests
3+
category: 62cc6ce22b8b6601da6cb12d
4+
---
5+
6+
If the API you're using doesn't have any documented [operation IDs](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#user-content-operationid), `api` will generate some for you to use.
7+
8+
If you're using code generation, these will be immediately available to use in your generated library. However, due to the nature of the [Proxy](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy) architecture in the dynamic version of the library, this isn't the case for dynamically generated libraries. For these cases, you can check out the documentation for the API you're using.
9+
10+
> ⚠️
11+
>
12+
> We recommend using code generation as it'll give you the additional benefit of TypeScript type assistance and autocompletion (even if you aren't using TypeScript in your codebase).
13+
14+
With an instance of your SDK, you make an HTTP request against an operation on the API like so:
15+
16+
```js
17+
const petstore = require('@api/petstore');
18+
19+
petstore.listPets().then(({ data, status, headers, res }) => {
20+
console.log(`My pets name is ${data[0].name}!`);
21+
});
22+
```
23+
24+
Here, the data returned in the promise from `listPets` is an object containing the following data:
25+
26+
- `data`: The data that came back in the API request. Under the hood this is the result of `api` running `res.json()` or `res.text()` on the [Response](https://developer.mozilla.org/en-US/docs/Web/API/Response) object from the [Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API).
27+
- `status`: This is the HTTP status code of the response.
28+
- `headers`: The headers that came back in the response. This is an instance of the [Headers](https://developer.mozilla.org/en-US/docs/Web/API/Headers) object.
29+
- `res`: This is the raw [Response](https://developer.mozilla.org/en-US/docs/Web/API/Response) object we received from the [Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API).
30+
31+
## Error Handling
32+
33+
For every response that is returned with an HTTP status code between 400 and 599, `api` will throw a custom error: `FetchError`. Identical to how responses are returned from successful requests, instances of `FetchError` can be destructured to obtain the same data. For example:
34+
35+
```js
36+
await petstore.deletePet({ id: petId }).catch(({ status, data }) => {
37+
// status = 404
38+
// data = 'Not Found'
39+
});
40+
```
41+
42+
Alternatively if you'd like to check for an error other than `FetchError` (i.e., an error with the SDK itself), you can do that too:
43+
44+
```js
45+
await petstore.deletePet({ id: petId }).catch(err => {
46+
if (!(err instanceof FetchError)) {
47+
throw err;
48+
}
49+
50+
// err.status = 404
51+
// err.data = 'Not Found'
52+
});
53+
```
54+
55+
## Request Timeouts
56+
57+
By default, the [Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) generally has a default timeout of 30 seconds. If you wish to configure this, you can with the `.config()` method:
58+
59+
```js
60+
petstore.config({ timeout: 100 }); // 100 milliseconds
61+
62+
await petstore
63+
.deletePet({ id: petId })
64+
.then(() => {
65+
// goodbye, friend
66+
})
67+
.catch(err => {
68+
// err.message = The operation was aborted.
69+
});
70+
```
71+
72+
By supplying a timeout to `.config({ timeout })`, in milliseconds, `api` will automatically initialize an [AbortController](https://developer.mozilla.org/en-US/docs/Web/API/AbortController) to abort your request if it takes longer than your `timeout` value. Please note that if you set a custom timeout, the error that is thrown will be an instance of `AbortError`, **not** `FetchError`.
73+
74+
> 📘
75+
>
76+
> The `.config()` method is not chainable.

docs/parameters-and-payloads.md

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,10 +11,10 @@ When supplying parameters and/or request body payloads to an API request, you do
1111
For example, if you wanted to make a GET request:
1212

1313
```js
14-
sdk.showPetById({ petId: 1234 }).then(...)
14+
sdk.showPetById({ id: 1234 }).then(...)
1515
```
1616

17-
Since `petId` matches up with the `petId` path parameter, the SDK here will issue a GET request against `/pets/1234`.
17+
Since `id` matches up with the `id` path parameter, the SDK here will issue a GET request against `/pets/1234`.
1818

1919
What about a POST request?
2020

@@ -27,7 +27,7 @@ Since `name` here would correspond on `createPets` to request body payload, this
2727
What about operations that require both? Well you can mix them too!
2828

2929
```js
30-
sdk.updatePet({ name: 'Buster 2' }, { petId: 1234 }).then(...)
30+
sdk.updatePet({ name: 'Buster 2' }, { id: 1234 }).then(...)
3131
```
3232

3333
Since we've supplied two objects here, the SDK automatically knows that you're supplying both a `body` and `metadata`, and can make a PUT request against `/pets/1234` for you.

docs/server-configurations.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ sdk.server('https://{region}.api.example.com/{basePath}', {
1111
basePath: 'v14',
1212
});
1313

14-
sdk.get('/pets').then(...)
14+
sdk.getPets().then(...)
1515
```
1616

1717
When your request is executed, it will be made to `https://eu.api.example.com/v14/pets`. Alternatively if you don't want to deal with URL templates, you can opt to pass a full URL in instead:

docs/upgrading-from-v4.md

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
---
2+
title: Upgrading from v4
3+
category: 5d4c940cae4e610060475769
4+
---
5+
6+
If you're upgrading from v4 of `api`, welcome 👋 a lot's changed! With the introduction of v5, `api` now offers a complete [code generation offering](https://api.readme.dev/docs/usage#code-generation), complete with:
7+
8+
- Full TypeScript types (generated off your OpenAPI definition) 📖
9+
- Ability to export to TypeScript, CJS, and ESM compiled files 📦
10+
- Ability to run your SDK within a browser 🌍
11+
12+
It's neat, and you should check it out. 🥺
13+
14+
If you'd like to continue using the [dynamic syntax](https://api.readme.dev/docs/usage#dynamically) you will need to update how you're handling promises that are returned from API requests, but it shouldn't be too bad.
15+
16+
Here's what your `api` implementation may have looked like before under v4:
17+
18+
```js
19+
const petstore = require('api')('https://raw.githubusercontent.com/readmeio/oas-examples/main/3.0/json/petstore.json');
20+
21+
petstore.listPets().then(res => {
22+
console.log(`My pets name is ${res[0].name}!`);
23+
});
24+
```
25+
26+
And here's what it should look like now:
27+
28+
```js
29+
const petstore = require('api')('https://raw.githubusercontent.com/readmeio/oas-examples/main/3.0/json/petstore.json');
30+
31+
petstore.listPets().then(({ data }) => {
32+
console.log(`My pets name is ${data[0].name}!`);
33+
});
34+
```
35+
36+
If you were using the `.config({ parseResponse: false })` option, that option has been removed in favor of this new resolved data shape where we return `data`, `status`, `headers`, and `res` to you. You can see documentation on those [here](https://api.readme.dev/docs/making-requests).
37+
38+
And if you have any trouble or need help we're more than happy to give you an assist. https://github.com/readmeio/api/issues

0 commit comments

Comments
 (0)