Compare commits

...

58 Commits

Author SHA1 Message Date
Robert Wallach
5ad421b83e Update publishing.md 2018-03-16 11:45:42 -05:00
Robert Wallach
62e52154ff Update publishing.md 2018-03-06 14:24:47 -06:00
Ross McDonald
b49dd91b7d Rewrite object-inheritance article (#143)
* Rewrite object-inheritance article.

* Update object-inheritance.md
2018-03-02 15:27:08 -06:00
Robert Wallach
86157dff74 Update shared-params-responses.md 2018-03-02 14:56:18 -06:00
Robert Wallach
97a1d746bb Update overview.md 2018-03-02 12:40:45 -06:00
Marc MacLeod
5701344eba Merge pull request #123 from stoplightio/feature/add-shared-params-article
Add Shared Parameters and Responses Article
2018-03-02 12:23:30 -06:00
Robert Wallach
553f891665 Update contract-testing.md 2018-02-20 12:56:35 -06:00
Robert Wallach
96393e0548 Update contract-testing.md 2018-02-20 12:54:00 -06:00
Ross McDonald
bbe034155b Remove polymorphic objects article, since its pretty much the same things as object-inheritance. (#144) 2018-02-20 10:33:16 -06:00
Robert Wallach
1e5b92d1e6 Update send-http-requests.md 2018-02-15 12:55:26 -06:00
Robert Wallach
d15945effd Update overview.md 2018-02-13 15:49:19 -06:00
Robert Wallach
f5c635337b Update run-test-terminal.md 2018-02-13 14:45:34 -06:00
Robert Wallach
5b25599d63 Rename articles/modeling/contract-testing.md to articles/testing/contract-testing.md 2018-02-13 14:02:22 -06:00
Robert Wallach
9338378ae3 Create contract-testing.md 2018-02-13 13:56:59 -06:00
Robert Wallach
f6b008b34b Update json-introduction.md 2018-02-12 16:20:31 -06:00
Robert Wallach
2b527cf8b8 Update polymorphic-objects.md 2018-02-12 15:19:48 -06:00
Robert Wallach
5faed6b434 Update object-inheritance.md 2018-02-12 14:56:06 -06:00
Robert Wallach
c404418929 Update generating-schemas.md 2018-02-09 14:13:51 -06:00
Robert Wallach
d661caf299 Update generating-schemas.md 2018-02-09 14:12:31 -06:00
Robert Wallach
0ecbab6dc0 Create CODE_OF_CONDUCT.md 2018-02-08 16:34:34 -06:00
Robert Wallach
bd023bdcd0 Update shared-params-responses.md 2018-02-08 15:59:06 -06:00
Robert Wallach
61affc25aa Update shared-params-responses.md 2018-02-08 15:57:13 -06:00
Robert Wallach
5db1c2f78e Update openapi-validation.md 2018-02-08 15:08:17 -06:00
Ross McDonald
59a94242cb Add example sections 2018-02-08 14:59:48 -06:00
Robert Wallach
3c2755f9cf Update duplication-refs.md 2018-02-08 12:30:37 -06:00
Robert Wallach
2b41569b14 Update duplication-refs.md 2018-02-08 12:25:55 -06:00
Ross McDonald
9893203512 Update phrasing 2018-02-07 18:14:51 -06:00
Ross McDonald
8ca0bef42f Merge 2018-02-07 18:13:13 -06:00
Ross McDonald
5eedf20432 Updates 2018-02-07 18:11:24 -06:00
Marc MacLeod
ea1fac8cd9 Merge pull request #129 from stoplightio/feature/testing-variables
Add testing/variables articles
2018-02-07 17:51:45 -06:00
Marc MacLeod
b1610a8395 Update variables-context.md 2018-02-07 17:51:02 -06:00
Marc MacLeod
55cb340584 Update variables-environment.md 2018-02-07 17:35:40 -06:00
Marc MacLeod
b6f257d182 Update variables-overview.md 2018-02-07 17:27:25 -06:00
Marc MacLeod
86c0f8c63e Merge pull request #130 from stoplightio/feature/add-environments
Update Environments article
2018-02-07 17:13:09 -06:00
Marc MacLeod
8785635e7c Update environments.md
add dos and donts, re-work intro a bit, indicate private are merged over default variables
2018-02-07 17:12:33 -06:00
Robert Wallach
e6053aba82 Update shared-params-responses.md 2018-02-06 16:08:09 -06:00
Robert Wallach
b09cf8bfe8 Update scenarios-introduction.md 2018-02-06 16:02:37 -06:00
Robert Wallach
066ae7c113 Update scenarios-introduction.md 2018-02-06 15:40:22 -06:00
Robert Wallach
6e4767a637 Update how-to-create-models.md 2018-02-05 15:08:40 -06:00
Robert Wallach
cb64dab3a8 Update how-to-create-models.md 2018-02-05 14:58:08 -06:00
Robert Wallach
3fa8f6ecc4 Create help.md 2018-02-05 14:14:51 -06:00
Robert Wallach
6242466fbd Update variables-context.md 2018-02-05 13:49:38 -06:00
Robert Wallach
59e35071b0 Update environments.md 2018-02-05 13:42:21 -06:00
Ross McDonald
d7ef14a1eb Merge branch 'feature/testing-variables' of github.com:stoplightio/docs into feature/testing-variables 2018-02-02 16:46:34 -06:00
Ross McDonald
fe5e946afe Clarify what curly brackets are. Other minor updates and clarifications. 2018-02-02 16:45:47 -06:00
Robert Wallach
60edd173dd Update variables-context.md 2018-02-02 15:54:27 -06:00
Ross McDonald
64a8a95921 Small update to resolved variables section. 2018-02-02 15:35:15 -06:00
Ross McDonald
4fdb7ea483 Update environments 2018-02-02 15:20:45 -06:00
Ross McDonald
7285d7a9e1 First drafts of all three articles. 2018-02-02 14:28:17 -06:00
Robert Wallach
213dbf5a28 Update how-to-create-models.md 2018-02-02 13:46:11 -06:00
Robert Wallach
a1d30d546c Add files via upload 2018-02-02 12:47:09 -06:00
Robert Wallach
ffc0a7c8aa Create how-to-create-models.md 2018-02-02 12:32:13 -06:00
Robert Wallach
27c4408da0 Update shared-params-responses.md 2018-02-02 12:14:12 -06:00
Ross McDonald
a669d9a077 Update section about format validation. 2018-02-02 10:06:12 -06:00
Robert Wallach
641ba7de6b Update shared-params-responses.md 2018-02-01 17:09:53 -06:00
Robert Wallach
3cbdf0911a Update ref-other-sources-hubs.md 2018-02-01 15:16:26 -06:00
Robert Wallach
4f95c171e4 Update api-models.md 2018-02-01 14:57:34 -06:00
Ross McDonald
5ecbf1d6f9 First pass at shared-params-responses 2018-02-01 13:16:38 -06:00
39 changed files with 1317 additions and 33 deletions

46
CODE_OF_CONDUCT.md Normal file
View File

@@ -0,0 +1,46 @@
# Contributor Covenant Code of Conduct
## Our Pledge
In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environment include:
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention or advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a professional setting
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.
## Scope
This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at robbins@stoplight.io. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version]
[homepage]: http://contributor-covenant.org
[version]: http://contributor-covenant.org/version/1/4/

View File

@@ -21,13 +21,3 @@ When you start the Stoplight desktop app, it will start an instance of Prism on
* The Stoplight desktop app can read/write specification files on your local file system. This is perfect for generating specification outside of Stoplight (like from code), want to use version control systems like Git, or want to use your favorite IDE to work on a spec.
* This feature is **NOT** available in the web app
the web app
<!--stackedit_data:
eyJoaXN0b3J5IjpbMTU3NDc5MjY0XX0=
-->

View File

@@ -1,25 +1,51 @@
# Environments
![](../../assets/gifs/editor-configuration.gif)
<!--(FIXME - SHOW CLICKING BETWEEN DIFFERENT ENVIRONMENTS)-->
The Stoplight editor includes an embedded configuration system that can be used to auto-populate environment information and other variables (hostnames, ports, passwords, etc.) utilized by specifications, scenarios, or collections. To setup the editor configuration, click the icon towards the top right of the editor screen immediately to the left of your username.
An environment is simply a container for data, represented as a list of key-value pairs (behind the scenes, this is a JSON object). Every Stoplight project has one or more environments associated with it. The data stored in an environment can be used in many places within the Stoplight editor.
![](../../assets/images/editor-configuration.png)
Environments, and their default data, are defined in the [Stoplight configuration file](./editor-configuration.md#environments).
- __Do__ create an environment for each development environment associated with the project. For example, `development`, `staging`, and `production`.
- __Don't__ create environments for individual users. Instead, use private variables (below) to customize existing environments.
- __Do__ use environment default data to store shared information like hostnames, ports, passwords, etc.
- __Don't__ use environments to store fixture/seed/temporary data.
<!--(FIXME - SHOW SCREENSHOT OF THE ENVIRONMENTS WINDOW)-->
For more information on environment variables and how they can be used during API testing, please
see [here](../testing/variables-environment.md).
## Private Variables
The left-half of the configuration window is dedicated to "Private Variables", which are variables that are _only_ stored locally on your system and are never sent to Stoplight. Private Variables should be reserved for secrets specific to you, such as user-specific passwords, API keys, and other pieces of sensitive data.
Private Variables are _only_ stored locally on your system,
and are never sent to Stoplight or the rest of your team. Private variables
should be reserved for secrets specific to you, such as user-specific passwords,
API keys, and other pieces of sensitive and/or individually specific data.
## Resolved Variables
Edit private variables by clicking on the environment button in the top right of the Stoplight editor.
The right-half of the configuration window displays "Resolved Variables", which is a read-only view of the variables currently exposed to your editor based on your current environment. These variables are stored in the `.stoplight` file included in your project (under "Config" in the File Explorer). To update the default or environment-specific variables stored in Stoplight, click the "Manage Environments" button under the configuration window.
> Since private variables are only stored on your computer, make sure they are
backed up in a secure location.
![](../../assets/gifs/editor-configuration2.gif)
## Resolved Variables
Variables stored in your configuration are in JSON, and can be referenced using the following format:
Resolved Variables shows a read-only view of the variables that are currently
exposed to your editor. They are based on:
```
{$$.env.myVariable}
```
* The currently selected (active) environment
* The active environment's default variables, as defined in the stoplight configuration file
* The active environment's private variables, as defined by you
Where `myVariable` is the name of the variable in your configuration.
Private variables are merged over default variables that share the same name. This makes it easy
for individual team members to customize and extend environments without affecting the rest of the team.
For more information on updating and customizing environment variables, please
see [here](./editor-configuration.md#environments).
***
**Results**
* [Using Environment Variables in Testing](../testing/variables-environment.md)
* [Configuration with the `.stoplight.yml` File](./editor-configuration.md#environments)

5
articles/help.md Normal file
View File

@@ -0,0 +1,5 @@
# Contact Us
Having trouble finding what you are looking for? Need some additional support? Weve got you covered. Shoot us a message and we will get back to you as soon as possible.
Email us at [support@stoplight.io](mailto:support@stoplight.io) or message us in Intercom.

View File

@@ -1 +1,32 @@
# Publishing
## What
Publishing your documentation has never been easier. Stoplight has added:
- New **Integrations** for Segment, Intercom, and Google Analytics to allow for traffic monitoring and additional analytics
- New **Authorizations** to make sure your documentation is secure at all times. This includes basic user/password authentication and SSO provider integration, powered by Auth0, SAML, and more.
- New **Builds** section for tracking published Hubs, including when a Hub was published, who published it, and under what domain.
Take that Gutenberg!
## Who
- **Organization Owners**, **Account Owners**, and **Administrators** can publish Hubs
## How
1. From the Stoplight editor, click on **Publish** in the far left-hand toolbar
2. Input a **subdomain** under Stoplight's tech-docs.io domain
- Or input a **custom domain** (optional)
3. Once completed, click **Next ->**
4. Select the Hub you wish to publish under **Hub File**
5. Add Integrations to **Segment**, **Intercom**, and **Google Analytics** under Integrations (optional)
6. Add security via **Username/Passwords Login**, **Auth0**, or **SAML** (optional)
7. Once completed, click **Publish** in the top left
8. A confirmation window will ask you to confirm your selection, click **Okay**
9. Once confirmed, **Build Logs** will display your current progress
- The process usually takes 2-5 minutes
10. Once the process has completed, a **green success message** will display at the bottom of the screen, letting you know that the Hub was published succesfully
11. Once a Hub is published, it will appear under **Builds**
12. To unpublish a Hub, select **Unpublish** in the **Danger Zone** underneath **Builds**
- If you wish to delete all builds and release the domain you are currently using, select **Remove Domain**

View File

@@ -5,7 +5,7 @@
## What
Hubs allows you to reference other sources to automatically populate your Hub with content. We call this “powering” a building block. You can power a building block with a file from the current file, a file from the current project, a file from another project, or a file from an external source.
### What can I Power
### What Can I Power
- Pages
- Subpages
@@ -16,17 +16,14 @@ Hubs allows you to reference other sources to automatically populate your Hub wi
### Power a Subpage
1. Select the Hub you wish to modify
2. Select (or create a new) Subpage
3. Click on the gear icon in the center of the editor toolbar (If new, this window automatically opens)
1. Select Power this Subpage with an External Data Source
2. Select (or create a new) **Subpage**
3. Click on the **gear icon** in the center of the editor toolbar (If new, this window automatically opens)
1. Select **Power this Subpage with an External Data Source**
2. Select the data source from the drop-down menu
3. Input the specific data source or select from the drop-down menu
4. Input an inner data source (optional)
4. Click Confirm
4. Click **Confirm**
<callout> Try it Out! Power a Subpage with an API Spec from the same project </>
<!-- theme: info -->
>Try it Out! Power a Subpage with an API Spec from the same project.

View File

@@ -1 +1,37 @@
# API Models
An API model is a blueprint that identifies the requirements and proposed solution for an API development project. A well crafted API model indicates you understand the problem you are trying to solve. The following steps can help you get started with creating an excellent API model.
## Identify Needs
During interactive sessions with stakeholders, outline all the requirements you want your API to meet . Some important questions to ask:
- What goal(s) do we want to achieve with the API?
- Who are the principal users that will consume or interact with the API?
- What activities will the users execute?
- How can we group the activities into steps?
- What are the API methods that are required for these steps? (Place the methods into common resource groups.)
- What resources will the API expose?
- What permissions will we need?
This process may need to be repeated until the API development team is sure that all requirements are covered.
## Build a Common Vocabulary
Vocabulary is used in your API artifacts such as your data fields, resource names, identifiers, and documentation. Creating a standard vocabulary helps you:
- Communicate well with different audiences.
- Establish a standard or style guide that can be adopted by members of the API development team.
- Easily update your documentation.
## Identify Resource Relationships
If your resources contain references to other resources or contain child resources, it is important to understand and define the types of relationships between resources because this will help you to show the link between the resources to the API user making the API more readable. Relationships can be:
- **Dependent**: the resource cannot exist without a parent resource.
- **Independent**: the resource can stand on its own and can reference another resource but does not need another resource to exist or function.
- **Associative**: the resources are independent but the relationship includes or needs further properties to describe it.
## Create a Test Plan
Ensuring that your API meets predefined criteria requires testing. Design test plans early. Feasible tests you can execute include:
- **Functional Testing**: Test the API calls to ensure that it delivers or behaves as expected. For example, you can test to see that the API delivers the expected data based on your model.
- **Mocking** (service simulation): Mocking allows you to execute tests on an API deployment without calling it through a defined API key. Effective API tools will allow you to test your API before implementation.
- **Load Testing**: How will your API perform when deployed on a production server? A load test is one way to simulate the effect of traffic on your servers and observe the performance of your API when it is available to users. Doing a load test will help you understand your API threshold and if the users exceed the threshold.
## Additional Notes
- Create tests that match your use case.
- Discuss security issues during your modelling meetings with your team.
- Ensure the test case is executed to see if the security issues are addressed before deployment. Click here to know more about security schemes and how to secure your API using best practices.

View File

@@ -1 +1,129 @@
# Preventing Duplications and Simplifying OAS Files
## What
- API resources often have or share similar features
- Duplicating features increase the size and complexity of your API
- Reusable definitions make it easier to read, understand, and update your OAS files
- Similar features can be created as reusable definitions and utilized with references
- These definitions can be hosted on the same server as your OAS file or on a different server
- You can reference a definition hosted at any location or server
- Apart from defining reusable definitions, you can also define reusable responses and parameters. You can store your reusable definitions, responses, and parameters in a common library.
<!-- theme: info -->
>Key Terms: A definition is a named schema object. A reference is a path to a declaration within an OAS file.
## How to Reference a Definition
To invoke a reference to a definition, use the **$ref** keyword. For example:
```
#/definitions/Pets ($ref: 'reference to definition')
```
## URL, Remote, and Local References
### General Syntax for URL Reference
- Reference a complete document or resource located on a different server:
```
$ref: 'http://url_resource_path'
```
- Reference a particular section of a resource stored on a different server:
```
$ref: 'http://url_resource_path/document_name.json#section'
```
### General Syntax for Remote Reference
- Reference a complete document or resource located on the same server and location:
```
$ref:'document_name.json'
```
- Reference a particular section of a resource stored on a different server:
```
$ref: 'document_name.json#section'
```
### General Syntax for Local Reference
- Reference a resource found in the root of the current document and the definitions:
```
$ref: '#/definitions/section'
```
## Best Practices
- Only use $ref in locations specifed by the OpenAPI Specification
- Always enclose the value of your local reference in quotes (when using YAML syntax) to ensure it is not treated as a comment. For example:
Good
```
"#/definitions/todo-partial"
```
Bad
```
#/definitions/todo-partial
```
## Examples
- Assuming you have the following schema object named **Todo Partial** and you want to use it inside another definition:
```
{
"title": "Todo Partial",
"type": "object",
"properties": {
"name": {
"type": "string"
},
"completed": {
"type": [
"boolean",
"null"
]
}
},
"required": [
"name",
"completed"
]
}
```
- To refer to that object, you need to add $ref with the corresponding path to your response:
```
{
"title": "Todo Full",
"allOf": [
{
"$ref": "#/definitions/todo-partial" (Reference)
},
{
"type": "object",
"properties": {
"id": {
"type": "integer",
"minimum": 0,
"maximum": 1000000
},
"completed_at": {
"type": [
"string",
"null"
],
"format": "date-time"
},
"created_at": {
"type": "string",
"format": "date-time"
},
"updated_at": {
"type": "string",
"format": "date-time"
},
"user": {
"$ref: "https://exporter.stoplight.io/4568/master/common.oas2.yml#/definitions/user" (Reference)
}
},
"required": [
"id",
"user"
]
}
]
}

View File

@@ -1 +1,61 @@
# Generating Schema
## What
- A schema is metadata that defines the structure, properties, and relationships between data. It also defines the rules that must be adhered to and is usually in the form of a document.
- A structured approach is always recommended for handling and manipulating data.
- The "$ref" keyword is used to reference a schema.
## Why
- A schema definition makes the process of handling data more structured.
- The process of validation and handling user input errors can be imprioved through the use of schemas.
- Schemas encourage the 'single source of truth' (single place to update a definition) concept which, among other things, makes it easier to create and maintain endpoints.
## Best Practices
- It is advisable to always use a schema when you define and implement your API.
- Use schemas to rapidly extract titles, descriptions, and samples for easy API documentation.
## JSON Schema
- JSON (Javascript Object Notation) is a popular, human readable data format that is easy to parse at the server or client side.
- JSON Schema is a standard that contains information about the properties of a JSON object that can be used by an API. It also helps validate the structure of JSON data.
-The properties include: name, title, type etc.
- JSON Schema Specification is divided into three parts:
- **JSON Schema Core**: describes the basic foundation of JSON Schema
- **JSON Schema Validation**: describes methods that define validation constraints. It also describes a set of keywords that can be used to specify validations.
- **JSON Hyper-Schema**: an extension of the JSON Schema Specification that defines hyperlink, images, and hypermedia-related keywords.
## Example
Assume you have an API that requires data provided in the format below:
```
{
pets: [
{id:1 petName: "Blaze", petType: "Canine", age: 2},
{id: 2, petName: "Felicia", petType: "Feline", age: 1}
{id: 2, petName: "Bolt", petType: "Canine", age: 3}
]
}
```
As seen above, each object in the pets array contains the following properties: id, petName, and petType. You can create a schema definition to validate the data and ensure it is in the expected format. The schema definition is outlined below:
```
{
"type":"object",
"properties": {
"pets": {
"type": "array",
"items": {
"type": "object",
"properties": {
"id": {"type": "number"},
"petName": {"type": "string", "required": true},
"petType": {"type": "number", "required": true},
"age": {"type": "number"}
}
}
}
}
}
```
### Related Articles
- [JSON Schema](http://json-schema.org/specification.html)

View File

@@ -0,0 +1,85 @@
# Models
## What
A model contains common reusable information that can be referenced in your endpoint definitions or other models in your API design. The resources or endpoints in your API project might contain duplicate structures and response objects. Models reduce this duplication by helping you extract and define common resources making your project easier to maintain.
## Best Practices
### Avoid Cluttered APIs
When you have several endpoints with the same structure, objects, and properties, your API design is untidy. Ensure that you extract reusable artifacts and build them as pragmatic models referenced by other resources within your API project.
### Use a Design First Approach
A design first approach helps create neat and consistent models. It will take longer, but it ensures you built an effective API that is easy to understand and maintain.
## How to Create Models using the Stoplight Modeling Editor
1. Create a new API project (link on how to create a new project goes here)
2. For this example we will be referring to endpoints created for a fictional Pet Store as listed below
- GET /pets (return all pets)
- GET /pets{petid} (return pet with a specified id)
- POST / pets (enter pet information)
- PUT /pets{petid} (update pet with a specified id)
- DELETE /pets{petid} (delete pet with a specified id)
3. The GET /pets method has an array of objects in the Response body with the following properties:
```
{
id, (string),
name, (string),
date _created (string, date format),
date_updated (string, date format),
approved (Boolean),
approved_by (string)
}
```
4. The GET /pets {petid} method duplicates the objects above with the same properties:
```
{
id, (string),
name, (string),
date _created (string, date format),
date_updated (string, date format),
approved (Boolean),
approved_by (string)
}
```
5. The PUT / pets{petid} method duplicates the object above in the Response body with a slight difference in the Request body which has the objects and properties below:
```
{
id, string,
approved boolean,
approved_by string
}
```
<!-- theme: info -->
>Duplication of Objects: If you are required to make changes you would have to update this information in three or more endpoints. Creating a model solves this issue.
6. To create a model click on the + sign next to the Model section.
![](../../assets/images/create-model.png)
7. Enter the details for the key, title, and description fields
![](../../assets/images/editor-details.png)
8. Click on the Editor Tab to create the object and specify the properties you want in the model (You can also copy and paste the JSON Schema from an endpoint into the Raw Schema section of the model)
![](../../assets/images/create-object.png)
![](../../assets/images/model-design.png)
9. Click the Save button to save the changes you have made in the editor
10. Select the GET /pets {petid} (or any endpoint) and navigate to Responses→ Editor
11. To reference the model in your endpoint, click on the object and select $ref as the array item type. Select the model you created from the drop down list
![](../../assets/images/ref-model.png)
12. Select the Viewer section to see the changes you have made
![](../../assets/images/viewer-ref-model.png)
13. All changes made to the properties of the object in the model are now automatically updated in all endpoints that make a reference to the model

View File

@@ -1 +1,25 @@
# Introduction to Objects in API Document Structure
- An OpenAPI document is a document that describes an API and conforms to the OpenAPI Specification. These documents can be in YAML or JSON format.
- Your OpenAPI document can be a single document or a combination of several associated resources which use the $ref syntax to reference the interrelated resources.
## Primitive Data Objects Supported in an OpenAPI Document
- integer (int32 and int64)
- number (float and double)
- string
- byte
- binary
- boolean
- date
- dateTime
- password
## Additional OpenAPI Objects
- **Info Object**: describes the API's title, description (optional), and version metadata. It also supports other details such as contact information, license, and terms of service.
- **Server Object**: identifies the API server and base URL. You can identify a single server or multiple servers and describe them using a description field. All API paths are relative to the URL of the server, for example, "/pets" when fully dilineated, may describe "http://api.hostname.com/pets."
- **Paths Object**: outlines relative paths to individual endpoints within your API and the operations or HTTP methods supported by the endpoints. For example, "GET/pets" can be used to return a list of pets.
- **Parameter Object**: describes a single operation parameter. Operations can have parameters passed through by several means such as: URL path, query string, cookies, and headers. Parameters can be marked as mandatory or optional, you can also describe the format, data type, and indicate its depreciation status.
- **Request body object**: describes body content and media type. It is often used with insert and update operations (POST, PUT, PATCH).
- **Response object**: describes the expected response which can be referenced using the $ref syntax or described within the document. It associates an HTTP response code to the expected response. Examples of HTTP status codes incldue the 200-OK or 404-Not Found codes. [Click here for more information on HTTP Response codes](https://en.wikipedia.org/wiki/List_of_HTTP_status_codes).

View File

@@ -1 +1,143 @@
# Object Inheritance
## What
* A **model** contains properties that can be reused and referenced by endpoint
definitions, shared objects, and other models. For more information on what
models are and how they can be used, please see the API model overview
[here](./api-models.md).
* **Inheritance** is when a model derives its properties from another model.
* When a model inherits properties from another model, the model being inherited from is
known as a **base type** (or parent). A model that is inheriting
properties from a base type is known as a **derived type** (or child).
* When a base type inherits properties from another model, any derived types
will also automatically inherit the properties as well. For example, if model
C is a derived type of model B, and model B is a derived type of model A, then
model C is also a derived type of model A. In mathematics, this is known as
the [transitive property](https://en.wikipedia.org/wiki/Transitive_relation).
* To specify that a model should inherit from a base type, use the **allOf**
option (under "Combination Types") when building the model. By specifying
allOf and referencing the base type, the model will automatically inherit all
of the parent model's properties. A model can also inherit from multiple base
types as needed.
## Why
* Inheritance makes your API design more compact. It helps avoid duplication of
common properties and fields, reducing the complexity of the specification and the chance of errors.
## Best Practices
<!-- theme: info -->
> Avoid using contradictory declarations such as declaring properties with the
> same name but dissimilar data type in your base model and derived model.
### Example
As an example, imagine you are creating an API that stores and categorizes
different types of vehicles. To begin working on the API, you will need a base
"car" model with a few attributes that are common across all vehicles. This
might look similar to:
```javascript
// the car base type
{
"type": "object",
"properties": {
// number of wheels
"wheels": {
"type": "integer"
},
// number of doors
"doors": {
"type": "integer"
},
// brand of car
"make": {
"type": "string"
},
// model of car
"model": {
"type": "string"
}
}
}
```
<!--FIXME Insert image of creating model from UI -->
Now that we have a base type model, we now need a derived type that extends the
base type. Since we're dealing with cars, let's create a model that defines a
SUV type (or a Sport Utility Vehicle):
```javascript
// the SUV model
{
"allOf": [
// a reference to the car base type
{
"$ref": "#/definitions/car"
},
// properties that are only applied to the SUV model
{
"type": "object",
"properties": {
// whether the vehicle can go "off road"
"off-road": {
"type": "boolean"
},
// the amount of ground clearance
"ground-clearance": {
"type": "integer"
}
}
}
]
}
```
<!--FIXME Insert image of creating derived model in UI -->
As shown above, by wrapping our SUV model inside of an `allOf` block, we are
able to include all of the properties that are included in the car base model
above.
When fully de-referenced (the car reference is replaced with the car
properties), the derived SUV model will have the following JSON properties:
```javascript
{
"type": "object",
"properties": {
// number of wheels
"wheels": {
"type": "integer"
},
// number of doors
"doors": {
"type": "integer"
},
// brand of car
"make": {
"type": "string"
},
// model of car
"model": {
"type": "string"
},
// whether the vehicle can go "off road"
"off-road": {
"type": "boolean"
},
// the amount of ground clearance
"ground-clearance": {
"type": "integer"
}
}
}
```

View File

@@ -2,11 +2,35 @@
![](../../assets/gifs/file-validation-oas-spec.gif)
## What
OpenAPI validation is the process of verifying the underlying OpenAPI file syntax by making sure it conforms to the [OpenAPI Specification requirements](https://github.com/OAI/OpenAPI-Specification#the-openapi-specification) provided by the [OpenAPI Initiative](https://www.openapis.org/). Stoplight immediately validates any changes done to a spec to ensure they are in the correct format prior to being saved.
<!-- theme: info -->
> Stoplight currently supports the OpenAPI v2 specification. We are working on support for OpenAPI v3, and should have more information in the coming months.
## Why
- Validation promotes data integrity in your data store. For example, a user making updates during a PUT operation might omit data for an important property and overwrite valid data, compromising data integrity.
- Validations indicates that you are engaging in good design practice and your API design is consistent.
## Best Practices
- All requests made to an API should be validated before processing
- Mark all mandatory properties as **Required** to ensure that the value of the property is provided
- Assign a default value to optional properties or parameters with missing values. The server will use the default value when a value is missing or not provided
- You can use the keyword **ReadOnly** to designate a property that can be sent in a response and should not be sent in a request
<!-- theme: info -->
> Using a default value is not recommended when a property or parameter is mandatory
- An API can comsume different media types, the accepted media type can be specified using the **consume** keyword at the operational level or root level to define acceptable media types. For example:
```
consumes:
multipart/form-data
or
consumes:
application/json
```
- An HTTP response containing a user friendly error description is useful when validation fails
***
**Related**

View File

@@ -1 +0,0 @@

View File

@@ -1 +1,194 @@
# Shared Parameters and Responses
While designing API's in Stoplight, it is common to have multiple endpoints
share a set of query parameters and API responses. To help reduce extra
work (and the chance of introducing errors), it is important to:
* Identify endpoints with common parameters
* Use _shared components_ to reference the same property multiple times instead
of rewriting the properties for each individual endpoint.
Shared components in Stoplight come in two forms:
* __Parameters__ - These are shared parameters that can be applied to requests
across multiple endpoints.
* __Responses__ - These are shared response objects that can be applied to
multiple endpoints.
## Parameters
Shared parameters provide a way to use request properties across multiple API
endpoints without having to duplicate effort.
![](../../assets/gifs/shared-params-responses-param.gif)
Shared parameters are supported in the following request property locations:
* __path__ - The request URL path
* __query__ - The request URL query string
* __header__ - The request HTTP Header field object
* __body__ - The request HTTP message body
* __form-data__ - The request HTTP message body in the `multipart/form-data` format
<!-- theme: info -->
> For more information the above properties, see the [OpenAPI v2 Specification](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#parameter-object)
Similar to generic request parameters, restrictions on the parameter values can
also be applied based on type, expected default value, minimum/maximum length,
and regular expression (regex).
![](../../assets/images/shared-params-responses.png)
To use a shared parameter, navigate to an API endpoint's _Request_ section and
create a reference to the shared parameter using the "chain" button as shown in
the image above. Once the parameter has been referenced, any updates to the
shared parameter will automatically be propagated to every endpoint using that
parameter.
![](../../assets/gifs/shared-params-responses-param2.gif)
Like other references in Stoplight, shared parameters can also be shared across
files, projects, and other external sources.
### Shared Parameters Example
Let's say you are creating an API to serve thousands of cooking recipes. When dealing with large volumes of
data, you typically want to avoid sending _all_ data in a request. To help avoid
sending more data than is necessary, most applications implement a "paging"
feature that allows clients to retrieve a small portion of results (i.e. a single
page).
There are multiple ways to approach a paging feature. For this example, we
want to add two query string parameters to every request:
* `limit` - The number of results to return when viewing a page. For example,
setting `limit` to `20` means that, at most, 20 results will be returned in the
request.
* `offset` - The number of results to skip before returning results. For
example, setting an `offset` of `20` means that the API will discard the first
20 results.
By using the two parameters above, a client can efficiently "page" through
results, only returning items that are within the requested bounds. To demonstrate, let's use the parameters to display the first page of our recipe
results:
```
GET /recipes?limit=20&offset=0
```
Since the `offset` is set to `0`, the API will not discard any results. Paired
with a `limit` of `20`, we will only see the first 20 results (1 through 20).
To view the second page of recipes, we would use:
```
GET /recipes?limit=20&offset=20
```
By setting an `offset` of `20`, the API will discard the first 20 results. Paired
again with a `limit` of `20`, we will see the second page of results (21 through
40).
### How
Now that we know how we want the components to behave, let's create them in
Stoplight. To get started, create a new shared parameter for an OpenAPI file
under the "Shared" section of the menu.
![](../../assets/images/shared-params-responses2.png)
As shown in the image above, set the properties for each parameter based on our
requirements:
1. Be sure to set the display names for both components properly. In our
example, we only have two parameters, however, if there are multiple shared
parameters with similar names, you may want to set a more descriptive name
(i.e. 'recipe-limit' instead of 'limit').
2. Since both components are query string parameters, set the property location
for each as 'query'.
3. Set the name of the parameter, which is how it will be set in HTTP requests.
4. Optional type restrictions can be applied to the values. In our case, since
both parameters are integer values, we can use the 'integer' format
restriction.
5. Setting a default value can be useful if you don't need the client to specify
each parameter for every request. For our example, it makes sense to set
defaults that will return the first page (limit of 20, offset of 0).
![](../../assets/images/shared-params-responses3.png)
Once the shared parameters are created, reference them in any API endpoint under the
__Query Parameters__ block of the request section in the editor.
## Shared Responses
Shared responses provide a practical way to re-use response objects across multiple API
endpoints without having to duplicate effort. Similar to the shared components
discussed above, shared responses allow you to reference a single response
multiple times without having to recreate each response manually. The added
benefit of this approach is that updates to the shared response object are
automatically propagated to any endpoint using that object, no extra changes
required.
![](../../assets/gifs/shared-params-responses-response.gif)
Shared responses allow you to configure the following properties:
* Headers - Customize the HTTP Headers returned in the response
* Response body - Customize the HTTP message body contents using the Stoplight
modeling tool (or reference a pre-existing model)
<!-- theme: info -->
> For more information on the above properties, see the OpenAPI v2 Specification
[here](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#responseObject)
![](../../assets/gifs/shared-params-responses-response2.gif)
To use a shared response, navigate to an API endpoint's __Response__ section and
create a reference to the shared response by choosing the _Type_ of the response
as "Reference". Once the Response type is set to "Reference", you can then
choose the shared response to use for that endpoint. Shared responses can also
be shared across files, projects, and other external sources.
### Shared Responses Example
Let's say you have a set of
API endpoints that should return the same error response when a failure occurs.
Every time an error is returned from the API, you want to make sure the
following properties are returned:
* `error_message` - A descriptive error message about the failure in string format.
* `error_code` - A code representing the category of the failure in integer format.
* `tracking_id` - A tracking ID that can be used by the caller to follow-up with
an administrator for more information (ie, debug an issue with customer
support).
Now that we know what should be returned, let's create a shared response in
Stoplight. To get started, create a new shared response for an OpenAPI file
under the "Shared" section of the menu.
![](../../assets/images/shared-params-responses4.png)
As shown in the image above, set the properties for each portion of the response
based on our requirements:
1. Set the name of the shared response. In our example, we only have one error
type, however, if there are multiple error responses with similar names, you
may want to set a more descriptive name (ie, 'api-tracking-error' instead of
'error').
2. A short description of the error response, such as why it is needed and how
it is used.
3. The contents of the shared response object based on the three required
properties above.
![](../../assets/images/shared-params-responses5.png)
Once the shared response is created, it can be referenced in any API endpoint by
using a _Reference_ type under a response. A shared response can also be used
multiple times under the same endpoint.
***
**Related**
* [OpenAPI v2 Parameter Objects Reference](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#parameter-object)
* [OpenAPI v2 Response Objects Reference](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#responseObject)

View File

@@ -0,0 +1,62 @@
# Prism Introduction
Prism is a performant, dependency free server, built specifically to work with web APIs.
### Features
- Act as a mock server, routing incoming requests to example repsonses, or dynamically generating examples on the fly.
- Act as a transformation layer, manipulating incoming requests and outgoing responses.
- Act as a validation layer, validating incoming requests and outgoing responses.
- Contract test your APIs, given an OAS(Swagger 2) file.
- Log all or a subset of traffic to configurable locations.
- Extend existing APIs with new endpoints or capabilites.
- Act as a system-wide proxy, blocking traffic to particular websites or endpoints.
### Simplicity Redefined
Run it anywhere. It runs on OS X, Windows, and Linux, with no external dependencies. It is a single, self-contained binary file, that you can easily run from your terminal with a single command.
## Getting Started
#### macOS and Linux
```# Install Prism
curl https://raw.githubusercontent.com/stoplightio/prism/master.install.sh | sh
```
#### Windows
Download the appropriate binary from [here](https://github.com/stoplightio/prism/releases). Unzip the binary file, then navigate in your terminal to the folder where you extracted Prism.
### Run a Simple Mock Server
Prism understands OAS(Swagger 2), so let's get started by spinning up a quick mock server for the popular Petstore API. To do this, run the following command in your terminal:
```# os x / linux
prism run --mock --list --spec http://petstore.swagger.io/v2/swagger.json
# windows
path/to/prism.exe run --mock --list --spec http://petstore.swagger.io/v2/swagger.json
```
Here, you are using the "run" command to run a server based on the spec file passed in via the --spec argument. The spec location can be the filepath to a file on your computer, or the URL to a publicly hosted file. The --mock argument tells Prism to mock all incoming requests, instead of forwarding them to the API host described in the spec file. The --list argument is a convenience, and tells Prism to print out the endpoints in the spec on startup.
Prism starts on port 4010 by default - try visiting ```http://localhost:4010/v2/pet/findByStatus``` in your browser. This is one of the endpoints described in the petstore spec you passed in. You'll notice that it returns an error about a required query string parameter "status". This is the automatic request validation at work! The swagger spec specifies that a query string parameter names "status" is required for this endpoint so Prism simulates a 400 response for you. Reload the page with a query string parameter, and you will see the dynamically generated mock response ```http://localhost:4010/v2/pet/findByStatus?status=available```.
Tada! With a single command you have started a validating, dynamically mocking version of the Swagger petstore API.
### Run some Contract Tests
Prism consumes OAS(Swagger 2) files. OAS provides the contract for your API. If your OAS file contains the x-tests extension (generated automatically if you use the Stoplight app to manage your OAS and tests) then you can run tests with Prism.
Check out [this specification](https://goo.gl/jniYmw). If you scroll past all the regular OAS properties, you will notice a ```x-tests``` extension near the bottom of the file. Inside of that property, we have a few test cases defined. This OAS file, along with its tests, is managed in the Stoplight app (we export our API from within the app to produce this file).
#### To Run the Contract Tests
```
# os x / linux
prism test --spec https://goo.gl/jniYmw
# windows
path/to/prism.exe test --spec https://goo.gl/jniYmw
```
You should see some nice output to your terminal detailing the tests and assertions that are run. These tests take our OAS contract and apply it to your API. They act as a sort of sync manager.
<!-- theme: info -->
> If a test fails, it means one of two things - your API is broken or, our OAS contract is out of date / incorrect

View File

@@ -0,0 +1,37 @@
# Contract Testing
Scenarios makes it easy to incorporate your OAS / Swagger API specification into your testing process. A few benefits to doing this include:
- **DRY**: Don't re-create test assertions that check for what is already described in your API contract.
- **Governance**: Quickly figure out if the API that was created actually conforms to the API design that was initially agreed upon.
- **Sync Manager**: Your API spec is the single point of truth that describes your API. From it, you might generate documentation, sdks, mock servers, etc. Incorporating your spec into your tests makes sure that your API spec accurately represents your API over time.
<!-- theme: info -->
> If you don't have an API specification yet, you can create one using the Stoplight modeling tool!
## Connecting The Spec
The first thing you need to do to get started with contract testing is connect your API spec to the Scenarios Collection.
1. Create a new (or open an existing) **Scenario file** in the Stoplight editor
2. Select **Swagger/OAS Coverage** in the Scenarios menu to the left
3. Open **Contract Test Settings**
4. Click **+ Add Spec**
5. Select a file from either **This Project** or an **External URL**
6. You are all set! You can now test against an API spec.
## Using the Coverage Report
The coverage report gives you a quick overview of which parts of the connected specs are covered by test assertions in the current Scenario Collection.
You can use the coverage report to quickly stub out a new scenario. Just click the status codes in the table matrix for the steps you want to add to your scenario (in order). Once you've added all the steps, click the "Create Scenario" button in the top right. This will create a scenario with as much setup as possible, using the connected spec for data. It will set your request body, set variables in a sensible way, automatically setup contract tests, and more.
You will likely need to tweak the resulting scenario a little bit, but this process will usually get you most of the way to a complete scenario, with contract test assertions in place!
## Automatic Contract Test Assertion
After linking your spec to the Scenario Collection, contract test assertions will be automatically added for step assertions.
Stoplight will look through your API specification for a operation that matches the step's HTTP method + URL, and use the response status code returned from the API to look up the JSON schema. In the example below, we are testing the 200 response schema in our API spec for the GET /todos/{todoId} endpoint.
When this step is run, the HTTP response structure will be validated against the matched JSON schema from our API spec, and any errors will be added to the test results.

View File

@@ -1 +1,80 @@
# Running a Scenario from Terminal
It is very easy to run scenario collections, or individual scenarios, on your own computer, completely outside of the Scenarios app.
First, install Prism, our command line tool for running scenarios.
*On macOs or Linux:*
```
curl https://raw.githubusercontent.com/stoplightio/prism/2.x/install.sh | sh
```
*On Windows:*
```
Download from https://github.com/stoplightio/prism/tree/2.x
```
After installing, you should be able to run `prism -h` (or `prism.exe -h` in Windows) and see some help text.
The Scenario app has a convenient display that gives you the exact command required to run the collection or scenario that you are viewing, taking into account your current environment variables. If you have the Scenario editor connected to a local file on your computer, it will use the path to that file, otherwise it will use the Scenario SRN (unique identifier).
<!-- theme: warning -->
> Keep in mind that if you are storing your Scenarios on Stoplight's servers, and running them from the command line, you must save them in the Stoplight app before running! This is because Prism will make a call to the Stoplight API to fetch your Scenario JSON, which it will then run from your computer.
See below for a screenshot of the "Run From Terminal" command generator. The command in this box will update live in response to environment, user, and scenario changes.
![](http://i.imgur.com/mqpNanE.png)
## Running Local Files
The `prism conduct` command accepts a filepath. So, if you are working with [local scenario collection](#docTextSection:Ap4Z2B7RgbbLFLjJD) .json files, you can run them with something like:
```bash
prism conduct /path/to/collection.json
```
## Including Specs For Contract Testing
If you are using [contract testing](#docTextSection:tFWniZdshJYLLtKms), you will need to include the filepath to the API specification as part of the command. This is what that looks like:
```bash
prism conduct myOrg/scenarios/myScenarios --spec /path/to/my/swagger.json
```
## Continuous integration
Most CI products (Circle CI, Travis, Jenkins, Codship, etc) generally function in the same way: setup environment, invoke commands to run tests. With Scenarios + Prism, the process is similar. Install Prism, and then configure the CI process to run the appropriate Prism command. We've included instructions for Circle CI below, but these concepts should loosely apply to other CI products.
#### Circle CI
Integrating [Prism](http://stoplight.io/platform/prism) into Circle CI is easy. All you need to do is install Prism and overide the test command.
To install Prism just add a dependency to your circle config.
``` yaml
dependencies:
pre:
- curl https://raw.githubusercontent.com/stoplightio/prism/2.x/install.sh | sh
```
Then override the default test command for circle in your config.
``` yaml
test:
override:
- prism conduct orgId/scenarios/scenarioId
```
When running `prism conduct` you can:
- Use the Scenario SRN, as displayed above.
- Include the Scenario JSON on your CI server, and pass in its absolute file path
- Pass in the absolute URL to the scenario JSON served up via HTTP.
<!-- theme: warning -->
> Don't forget to pass in any required environment values with the --env command line flag (or you can provide the filepath to a json file with your environment variables)!
For convenience, you can find the full command to run your scenario collection or individual scenario in the Stoplight app.

View File

@@ -1 +1,17 @@
Stoplight Scenarios is a powerful (but accessible!) tool that takes the pain out of API testing. It is a standalone product, available on [the web](https://scenarios.stoplight.io), and as a [desktop app](https://download-next.stoplight.io).
We generally recommend the desktop app when possible. It works with local servers, behind firewalls, and exchanges information with tools on your computer like Git or your favorite IDE. You can switch seamlessly between the desktop app and the web app.
We engineered Scenarios from the ground up to be:
- **Powerful** Easily assert, capture, transform, and validate your API Spec (Swagger) against your actual API. And if that isnt enough, Prism has a powerful javascript runtime.
- **Portable** Scenarios are described in plain JSON with a well thought out, robust specification. Use our visual editor to quickly generate and manage this JSON. They can be run from our visual tooling, or completely outside of Stoplight, on your own machines or on your continuous integration server.
- **Flexible** Your APIs, your tests, your way. Scenarios only test what you want them to. They have no opinion about your architecture (Monolithic vs Microservices), company structure (in house vs distributed), development lifecycle (production vs TDD), and your environment (development vs staging vs production).
- **Fast** Time cant be slowed down, and we cant give it back to you. Creating tests should be quick, and waiting for you tests to run shouldnt feel like watching water boil. Scenarios are run concurrently for maximum speed - run hundreds of API requests and test assertions in seconds.
### Editor UI Overview
![](https://cdn.stoplight.io/help-portal/scenarios/scenario-editor-callout.png)

View File

@@ -1 +1,50 @@
# Overview of Testing with HTTP Requests
## What are HTTP methods?
- Hypertext Transfer Protocol (HTTP) is a set of rules that define how information is requested, transmitted, and formatted between a client and a server. HTTP methods (verbs) are used to implement create, read, update, and delete operations on identified resources.
- HTTP methods are classified as safe, non-safe methods, idempotent or non-idempotent methods. Safe methods do not change the state of a resource. Idempotent methods, if executed severally, deliver consistent outcomes. An example of idempotency is outlined below:
### Example
- petAge = 2 # will always return 2 even when the statement is executed over and over again. This statement is idempotent.
- petAge++ # will return different results based on the number of executions. This statement is non-idempotent.
## Methods
- The **GET** method retrieves data and resource representation. It does not change the state of a resource and several executions produce the same results. Thus, it is a safe and idempotent method. When a GET method is successful, it should return a 200 (OK) HTTP status code with the content in the response body and a 404 (NOT FOUND) code if the resource is not available.
- The **POST** method creates new resources. The POST method is not safe and is non-idempotent as the execution of similar POST requests will create two different resources with similar details. It is suggested for non-idempotent resource requests.
- The **PATCH** method makes partial updates to a resource and it is non-idempotent.
- The **PUT** method updates a resource or creates a new resource if it does not exist. It is ideal for the complete update of a resource. The PUT method is idempotent but not safe.
- The **DELETE** method deletes a resource. It is idempotent but not safe.
### Summary
The GET method is the only safe method, as it does not change the state of a resource. GET, PUT, and DELETE methods are idempotent while the POST and PATCH methods are non-idempotent.
## Testing with HTTP Requests
- Testing using HTTP Requests demonstrates whether or not an API will perform as expected when it is deployed to a production server and integrated with existing platforms.
<!-- theme: info -->
> HTTP Request Tests should include checks to the response code, message, and body.
- Apart from verifying the functionality of essential features, HTTP Request Tests **save time and cost**.
## Testing with HTTP Requests: Best Practices
### GET
- Test the GET method to confirm it returns the correct data.
- Test a valid GET request to ensure it returns a 200 (OK) status code or 404 (NOT FOUND) if invalid
- Ensure you test every endpoint fetching data within your API before deployment to a production server.
### POST
- Test the POST method to confirm it creates a resource and returns a 200(OK) code and/or 201(CREATED) code if valid. If invalid, look for a 4xx error status code.
- You can use the GET method to see the outcome of the POST operation.
### PUT & PATCH
- The PUT and PATCH update methods should be tested to ensure that a 200(OK) status code or 204(NO CONTENT) is returned for a successful transaction. If unsuccessful, look for a 4xx error status code.
### DELETE
- Test the DELETE request to certify it returns a 4xx error code if a DELETE operation is executed against an invalid or non-existent resource.
- Test the DELETE request to confirm it returns a 200(OK) for a successful operation.
- Tests for the DELETE method **must not** be done with data residing on a production or live data store.
<!-- theme: info -->
> Testing is a critical stage of the API development life cycle and the type of tests executed will depend on the complexity of the API, time, budget, etc. It is vital to conduct robust tests to reveal any inconsistencies or defects in the API before it is shipped to a production server or interfaced with other platforms.

View File

@@ -1 +1,101 @@
# Using Context Variables
<!--(FIXME - SHOW WRITING VARIABLE TO CONTEXT IN STEP)-->
Context variables allow you to dynamically store and share data between steps in a scenario. Contrary to environment variables, context variables are _not_ saved once a test has completed. Therefore, context variables are only suitable for temporary data.
Context variables are scoped to the scenario, _not_ the collection. This means that two scenarios can both read/write the same context variable `myVar`, and not conflict with each other. Environment variables, on the other hand, are shared amongst all scenarios, and are scoped to the collection.
At the start of a test run, the context object is empty. Good examples of data to store in a context would be things like ID's, usernames, and randomly generated tokens.
## Use Case
Context variables make it possible to chain related steps together. For example, say we have the following set of actions to perform:
1. Create User, `POST /users`. Returns a new user object, with an `id` property.
2. Get User, `GET /users/{$.ctx.userId}`.
3. Delete User, `DELETE /users/{$.ctx.userId}`.
Somehow we need to use the `id` property for the user created in step #1 to build the request in steps #2 and #3. This is a great case for context variables, since the data is temporary (the new user's id changes every test run, and is only needed in this single scenario).
To accomplish this, we would capture/set the `$.ctx.userId` property to `output.id` in step #1, and then use that variable to create the request urls in #2 and #3 (shown above).
## Setting Context Variables
### With Captures
<!--(FIXME - SHOW USING THE CAPTURE MENU IN A SCENARIO STEP)-->
The capture UI in the step editor makes it easy to set `$.ctx` values. You can use values from the step output or input, including headers, response bodies, etc.
<!-- theme: info -->
> Multiple captures can be applied to the same step, to set multiple `$.ctx` values.
### With Scripting
<!--(FIXME - SHOW SCREENSHOT OF SCRIPT IN STEP)-->
Scripting allows you to use more complicated logic in a scenario step. Scripts
are executed either before or after a step request finishes. Scripts are plain
Javascript and give you direct access to the scenario context through the global
`$.ctx` object.
For example, if we wanted to set the `userId` property as described in the use case above, we would add an after script to the first step with the code:
```javascript
// store the step output body's 'id' property in the context, for use in subsequent steps
$.ctx.set('userId', output.body.get('id'));
```
Where the `$.ctx.set(x, y)` function adds the data referenced in the second
argument (`y`) to the context under the string value of the first argument
(`x`).
Here is another example that just sets `myVariable` to the hardcoded value `123`:
```javascript
$.ctx.set('myVariable', 123);
```
## Using Context Variables
<!--(FIXME - SHOW USING A CONTEXT VARIABLE IN A SCENARIO STEP)-->
To use a context variable in a scenario, use the following syntax:
```
{$.ctx.myVariable}
```
Where:
* `{...}` - Braces signify that this is a variable.
* `$` - The "single dollar sign" syntax is a reference to the current scenario's
runtime scope. Again, context variables are scoped to the individual scenario, not the global collection!
* `ctx` - This is the actual context object onto which values are stored and retrieved.
* `myVariable` - This is the name of the variable being referenced within the context.
When the scenario or step is run, all context variables will
automatically be populated based on the contents of the `$.ctx` at
runtime.
### In Scripts
Similar to the example above, when referencing a context variable in a step
script, use the following syntax:
```javascript
$.ctx.get('myVariable');
```
Where the braces (`{}`) are absent, and we are using the `get()` method for
retrieving the context variable under the `myVariable` key.
***
**Related**
* [Environment Overview](../editor/environments.md)
* [Environment Configuration](../editor/editor-configuration.md)
* [Variables Overview](./variables-overview.md)
* [Context Variables](./variables-context.md)

View File

@@ -1 +1,93 @@
# Using Environment Variables
<!--(FIXME - SHOW CLICKING THROUGH ENVIRONMENTS IN UI)-->
> If you have not already done so, we recommend reviewing the
[Environments](../editor/environments.md) article before continuing.
Environment variables in Stoplight allow you to dynamically retrieve information
in a scenario from the active environment. This makes it possible to
switch between different environments with ease, having variables automatically
populate based on the current environment.
## Setting Environment Variables
### With the Editor Configuration
For information on managing project environments, please review the [environment](../editor/environments.md) article.
### With Captures
Captures make it easy to "capture" values from your step request or result, and save them back to an environment variable for later use. Simply switch to the `captures` tab in the scenario step, and choose $$.env as the target property.
Say you have a scenario step that sends an HTTP request to authenticate a new user. The response from that request includes an apiKey that you want to use for other requests. You can easily save that apiKey to an environment variable, for later re-use, by adding a capture in the form `$$.env.apiKey = output.body.apiKey`. After running the step, check your current environment variables and note the newly added apiKey!
> Environment variables set via captures are only added to the user's private
variables, and are not sent to Stoplight. See the [Environment
section](../editor/environments.md) for more information.
### With Scripting
Scripting allows you to use more complicated logic in a scenario step. Scripts
are executed either before or after a step finishes. Scripts are plain
Javascript and give you direct access to the scenario environment through a
global `$$.env` object.
To add variables to the environment, use the following syntax:
```javascript
// store the step output (response) body's 'username' property in the environment
$$.env.set('username', output.body.get('username'));
```
Where the `$$.env.set(x, y)` function adds the data referenced in the second
argument (`y`) to the environment under the string value of the first argument
(`x`).
> Environment variables set via script are only added to the user's private
variables, and are not sent to Stoplight. See the [Environment
section](../editor/environments.md) for more information.
## Using Environment Variables
<!--(FIXME - SHOW USING A VARIABLE IN A SCENARIO STEP)-->
Use an environment variable in a scenario with the following syntax:
```
{$$.env.myVariable}
```
Where:
* `{...}` - Braces signify that this is a variable.
* `$$` - The "double dollar sign" syntax is a reference to the global
scope.
* `env` - The `env` property holds the active environment's data.
* `myVariable` - This is the variable being referenced, which comes from the
active environment's resolved variables. Substitute your own variable name when using
this in your scenarios.
When the scenario or step is run, any environment variables will
automatically be populated based on the editor's active environment.
### In Scripts
Similar to the example above, when referencing an environment variable in a step
script, use the following syntax:
```javascript
$$.env.get('myVariable');
```
Where the braces (`{}`) are absent, and we are using the `get()` method for
retrieving the environment variable under the `myVariable` key.
***
**Related**
* [Environment Overview](../editor/environments.md)
* [Environment Configuration](../editor/editor-configuration.md)
* [Variables Overview](./variables-overview.md)
* [Context Variables](./variables-context.md)

View File

@@ -1 +1,30 @@
# Variables Overview
Variables in Stoplight provide a powerful and intuitive way to dynamically set,
update, and retrieve information at any step in a Scenario.
Variables are stored in an [environment](../editor/environments.md). You can define one or more environments,
each with their own variables. This makes it easy to quickly swap out sets of
variables during testing.
There are a variety of circumstances where you might consider using variables instead of hardcoding the value, for example:
- __hostnames__: Instead of hard-coding a particular server location, use a variable
so that the host can quickly be changed to test multiple server locations (development versus production, for example).
- __api keys__
- __usernames and passwords__
- __ports__
- __path parameters__: Instead of defining a request `GET /users/123`, you can define a request `GET /users/{$$.ctx.userId}`.
There are two scopes for variables, which affect how and when they can be used.
* __Environment Variables__ - Environment variables are scoped to the project, and are shared amongst all steps in your test run. They are persisted between test runs, and are great for data that does not change often (hostnames, ports, etc). See [here](./variables-environment.md) for more information on how to use environment variables.
* __Context Variables__ - Context variables are scoped to the scenario, and are reset on every test run. They are useful to persist test and application state between scenario steps. Context variables are great for temporary information that is only relevant to the current test run. For example, you might store a newly created `userId` returned in your first step, to be used in the second step. This `userId` changes on every test run, which makes it a good context variable candidate. See [here](./variables-context.md) for more information on how to use context variables.
***
**Related**
* [Environment Variables](./variables-environment.md)
* [Context Variables](./variables-context.md)

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.5 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.3 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.0 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 50 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 38 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 130 KiB

BIN
assets/images/ref-model.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 108 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 41 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 52 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 50 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 75 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 52 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 48 KiB

34
size.sh Executable file
View File

@@ -0,0 +1,34 @@
#!/bin/bash
#set -x
# Shows you the largest objects in your repo's pack file.
# Written for osx.
#
# @see https://stubbisms.wordpress.com/2009/07/10/git-script-to-show-largest-pack-objects-and-trim-your-waist-line/
# @author Antony Stubbs
# set the internal field spereator to line break, so that we can iterate easily over the verify-pack output
IFS=$'\n';
# list all objects including their size, sort by size, take top 10
objects=`git verify-pack -v .git/objects/pack/pack-*.idx | grep -v chain | sort -k3nr | head`
echo "All sizes are in kB's. The pack column is the size of the object, compressed, inside the pack file."
output="size,pack,SHA,location"
allObjects=`git rev-list --all --objects`
for y in $objects
do
# extract the size in bytes
size=$((`echo $y | cut -f 5 -d ' '`/1024))
# extract the compressed size in bytes
compressedSize=$((`echo $y | cut -f 6 -d ' '`/1024))
# extract the SHA
sha=`echo $y | cut -f 1 -d ' '`
# find the objects location in the repository tree
other=`echo "${allObjects}" | grep $sha`
#lineBreak=`echo -e "\n"`
output="${output}\n${size},${compressedSize},${other}"
done
echo -e $output | column -t -s ', '