For this next project, we will be examining the test site Swagger Petstore - OpenAPI 3.0 at https://petstore3.swagger.io/
If we wanted to really dive deep into creating API documentation, we could use:
- I'dRatherBeWriting's Free Documenting APIs course, showing an Introduction to REST APIs, using APIs like a developer, Documenting API endpoints, the Open API spec, Testing API docs, Publishing API docs, and more...
... But that goes too deep for this blog post.
Before we begin, let's get into some background information.
What is Swagger?
According to OpenAPISpec.com's article, Who Created Swagger?, Swagger was created in 2010 by Tony Tam, the CTO of Wordnik, an online dictionary company that leveraged so many APIs, it was difficult for the six person engineering team to manage and scale them, writing API-clients and documentation by hand. After a 3 AM conversation, they thought... what if the API documentation could describe itself?
There already was WADL, the XML-based Web Application Description Language. The name was coined after a joke they made, "Why WADL when you can Swagger?"
Swagger went from being an internal fix for a company became to an open-source project other companies relied on.
Swagger was acquired by SmartBear Software in 2015 from the renamed Wordnik, Reverb Technologies. According to OpenAPISpec's What Is the History of the SmartBear Swagger Acquisition Tony Tam also joined SmartBear as the VP of Products. Smartbear donated the Swagger Specification to a new group, the OpenAPI Initiative, sponsored by the Linux Foundation.
I love SmartBear! They have hosted my old software testing Meetup, the now defunct Ministry of Testing - Boston many, many times.
Since then:
- "OpenAPI" is the OpenAPI Specification as seen on GitHub
- "Swagger" is SmartBear's toolset such as Swagger UI, Swagger Editor, Swagger Codegen, and SwaggerHub (soon to be Swagger Studio).
Where To Learn Swagger?
Luckily, there are many free places to learn Swagger, from both SmartBear and OpenAPI.- About Swagger: https://swagger.io/docs/specification/v3_0/about/
- OpenAPI 3.0 Tutorial: https://support.smartbear.com/swagger/studio/docs/en/get-started/openapi-3-0-tutorial.html
- SwaggerHub Introductory Training
- SwaggerHub API Designer
- Introduction to Contract Testing
- ReadyAPI Basics, Advanced, to learn about being an API Test Engineer
- Intro to API Hub for Contract Testing
- Training Portal: https://trainingportal.linuxfoundation.org/learn/dashboard
- OpenAPI Fundamentals: https://training.linuxfoundation.org/express-learning/openapi-fundamentals-lfel1011/
Open APIs:
- Learn.OpenAPIs.Org: https://learn.openapis.org/
- OpenAPI Spec 3.0.4: https://spec.openapis.org/oas/v3.0.4.html
- Leveraging OpenAPI to Test Your APIs
- Accelerate Adoption of OpenAPI with Test Automation
- Use OpenAPI Specs to Drive API Quality
What is Swagger Petstore?
The first version of the Swagger Petstore was a sample server app produced by Tony Tam and his engineering team when Wordnik first introduced Swagger, so others could check out Swagger's capabilities. It's not a real server.
This third version is now hosted by Smartbear, and is updated to Open API 3.0.
The page, https://petstore3.swagger.io/ is generated on-the-fly with Swagger UI, from the YAML file, https://petstore3.swagger.io/api/v3/openapi.yaml.
- Swagger Petstore Repo: https://github.com/swagger-api/swagger-petstore/tree/master
What is Swagger UI?
Swagger UI is a web application that reads an OpenAPI definition and renders interactive API documentation.
Swagger UI was developed as an open-source web application that could render a Swagger or OpenAPI specification into a human-readable way to examine an API, eliminating the need for developers and testers to manually read raw JSON or YAML API definitions.
Swagger UI allows users to browse API operations, inspect request and response schemas, authenticate against secured APIs, and execute live API calls directly from a browser.
Swagger UI was developed as an open-source web application that could render a Swagger or OpenAPI specification into a human-readable way to examine an API, eliminating the need for developers and testers to manually read raw JSON or YAML API definitions.
Swagger UI allows users to browse API operations, inspect request and response schemas, authenticate against secured APIs, and execute live API calls directly from a browser.
A few features of Swagger UI:
- Auto-Generated Documentation: Swagger UI reads your API schema file and dynamically creates a clean, organized webpage. It groups endpoints, shows paths, and lists response codes without requiring manual HTML coding.
- "Try It Out": Users can enter parameters, headers, and request bodies directly into the browser to execute live API calls against a real or mocked server and see the exact response in real-time.
- Clear Schema Models: It details the required data structures, object types, and validation constraints for every request and response, serving as an interactive contract for developers.
- No Dependencies: It is a client-side asset (built with HTML, JavaScript, and CSS) that runs entirely inside any modern web browser without needing a backend server or a database.
The Components of Swagger UI
You can use the Swagger UI to explore APIs in JSON or YAML format.
The OpenAPI document we are exploring is https://petstore3.swagger.io/api/v3/openapi.json.
If you open that URL directly in a browser, you won't see the formatted page. You'll see raw YAML file describing every endpoint, parameter, and data model.
The "Explore" button just tells Swagger UI to fetch and render whatever spec URL is typed into that box, which is handy if you're pointing the same Swagger UI instance at a different API's spec file.
The six models listed here are the core data types the Petstore is built around:
... Or even application/x-www.form-urlencoded:
- To the right of the name, the grey badge shows you the version of the API, and the green badge shows you which version of the OpenAPI Specification conforms to [Swagger UI Doc / version detection].
- Need to review the actual spec? It is provided in the link below the title.
- OpenAPI 3.0 spec includes a servers array that defines the base URL an array can be reached at. Every endpoint path, such as "/pet", will get appended to it... so /pet + /api/3 resolves to https://petstore3.swagger.io/api/v3/pet [ Swagger UI Doc / API Server and Base Path ]
- Servers can point to, say, a dev server, a staging server, and a production server.
- The Authorize button with the lock relates to the authentication scheme, such as an API Key, OAuth2, etc. Clicking on it lets you supply credentials so that "Try it Out" requests you send from the page contains them.
Below the Servers and Authorize button, you can see three groupings: pet, store, and user.
These tags are set up by the API developer designing this OpenAPI Yaml or JSON spec to group up common endpoints. If you expand pet, for example, you can see that it shows how you can interact with the /pet endpoint, such as with the HTTP Methods such as PUT, POST, GET and DELETE.
- GET retrieves data. It does not create, change, or delete anything on the server. In the Petstore, GET /pet/{petId} fetches one pet's details without touching it.
- POST creates something new, or submits data for processing. In the Petstore, POST /pet creates a brand new pet entry.
- PUT replaces an existing resource entirely with the data you send. In the Petstore, PUT /pet updates an existing pet. You send the pet's full data, including its ID, not just the one field that changed.
- DELETE removes a resource. In the Petstore, DELETE /pet/{petId} removes one specific pet by ID.The bottom section on the Swagger UI is the Schema section. Everything above the schema describes operations: what you can do, at which path, and with which method in the API.
The schema describes data, the reusable objects the operations pass around. In OpenAPI spec, they live in a components.schema field. [ See Swagger Docs / Spec / Basic Structure ].
The six models listed here are the core data types the Petstore is built around:
- Order: the format of a store order (what you'd get back from the store tag's order operations).
- Category: a pet's category, like "Dogs," which you actually saw nested inside the pet JSON examples in earlier screenshots.
- User: a user account record.
- Tag: not the same thing as the pet/store/user grouping tags from earlier; this is a data model representing a label attached to a pet (also visible nested inside the pet JSON examples).
- Pet: the main object type, the full shape of a pet record: ID, name, category, photo URLs, tags, status.
- ApiResponse: a generic response wrapper, commonly used for operations like uploadImage that return a simple status/message rather than a full resource.
Each of these schemas can be expanded to show the model's actual fields, data types, and if they are required.
Here, the schema can be defined once, with GET / PUT / POST, etc calls all getting the format of what a "Pet" actually is from this. New field? An API developer can just add it here.
What Is The Pet Schema?
If you expand the PET schema, you can see that it contains the fields, data types, and gives some examples of proper data you can submit:
- id: integer. Example: 10
- name (required): string. Example: "doggie".
- category: id (integer) and name (string). Example: "1. Dogs"
- photoUrls(required): name: photoUrl: wrapped: tru
- tags:
- status: "pet status in the store". Enum: available, pending, sold
When Photourls and tags are xml wrapped: true, it means the XML will use a parent element wrapper to encase all the items in the list, rather than just repeating the elements consecutively.
- <photoUrls> <photoUrl>string</photoUrl> <photoUrl>string</photoUrl> </photoUrls>
Examining the PUT /pet endpoint
The HTTP PUT request method updates and changes the parameters of an existing pet. POST creates a brand new one. GET retrieves the pet object. DELETE deletes them. And you can do that all through this Swagger UI.{
"id": 10,
"name": "doggie",
"category": {
"id": 1,
"name": "Dogs"
},
"photoUrls": [
"string"
],
"tags": [
{
"id": 0,
"name": "string"
}
],
"status": "available"
}... Application/xml...
<?xml version="1.0" encoding="UTF-8"?>
<pet>
<id>10</id>
<name>doggie</name>
<category>
<id>1</id>
<name>Dogs</name>
</category>
<photoUrls>
<photoUrl>string</photoUrl>
</photoUrls>
<tags>
<tag>
<id>0</id>
<name>string</name>
</tag>
</tags>
<status>available</status>
</pet>Update an existent pet in the storeThe Responses dropdown can show what a successful response would look like, after creating a new pet in the API with either application/json format:
id
integer($int64)
name *
string
category
object
photoUrls *
array<string>
tags
array<object>
status
string
{
"id": 10,
"name": "doggie",
"category": {
"id": 1,
"name": "Dogs"
},
"photoUrls": [
"string"
],
"tags": [
{
"id": 0,
"name": "string"
}
],
"status": "available"
}... or application/xml format...
<?xml version="1.0" encoding="UTF-8"?>
<pet>
<id>10</id>
<name>doggie</name>
<category>
<id>1</id>
<name>Dogs</name>
</category>
<photoUrls>
<photoUrl>string</photoUrl>
</photoUrls>
<tags>
<tag>
<id>0</id>
<name>string</name>
</tag>
</tags>
<status>available</status>
</pet>It also shows error codes such as:
- 400 Invalid ID supplied
- 404 Pet not found
- 422 Valid exception
- default Unexpected error.
422 is a new one to me. This means it is an Unprocessable Entity... the request was correctly formatted, but the data itself failed validation rules once the server tried to process the call. Like, say for example the status of a pet could only be "available", "pending" or "sold", and you put in "cuddly", it should throw a 422.
default is thrown when we do not explicitly catch an error. Example: If it is a 500 Internal Server Error, or a 401 Unauthorized, it displays that response, and not any of the special statuses we have put aside.
Examining the POST /user endpoint
Let's examine the POST Method for the /user endpoint, which creates a user if we are logged into the system.
{
"id": 10,
"username": "theUser",
"firstName": "John",
"lastName": "James",
"email": "john@email.com",
"password": "12345",
"phone": "12345",
"userStatus": 1
}If we see that it is successful, we will see a 200 Response.
{
"id": 10,
"username": "theUser",
"firstName": "John",
"lastName": "James",
"email": "john@email.com",
"password": "12345",
"phone": "12345",
"userStatus": 1
}If not, we will get nothing fancy, just a default, Unexpected error.
Examining the GET /user/login endpoint
After a user is created, the GET /user/login endpoint logs you into the system.
Next, we will be looking how to manually test this API using this Swagger UI.
No comments:
Post a Comment