Documenting REST APIs
-
Upload
tom-johnson -
Category
Technology
-
view
843 -
download
5
Transcript of Documenting REST APIs
DOCUMENTING REST APIS
BY TOM JOHNSON
IDRATHERBEWRITING.COM
STC Summit 2015 Columbus, Ohio @tomjohnson
CONVENTIONS
• Access the course module at http://idratherberwriting.com/restapicourse
• 1.1 Numbers in slide headings refers to the place in the course module.
• This icon indicates an activity you’re supposed to do.
• If you get lost, read the course page.
1.0 OVERVIEW
• Focus of the course is REST APIs
• Time to completion
• Learn with a real example and context
• No programming skills required
1.0 OVERVIEW
What you’ll need:
• Text editor• Chrome browser• Postman REST Client• cURL• Network connection
Follow along online: idratherbewriting.com/restapicourse
1.1 INTRODUCTION TO REST API DOCUMENTATION
Complete and accurate docs are most important factor in APIs
1.2 USING A REST API LIKE A DEVELOPER
Get an idea of the end goal
1.2 USING A REST API LIKE A DEVELOPER
Answer some questions about the API
• What does the API do?
• How many endpoints does the API have?
• What does each endpoint do?
• What kind of parameters does each endpoint take?
• What kind of response does the endpoint provide?
✔ Terminology tip: API == Endpoint
1.3 GET THE AUTHORIZATION KEYS
• Authorization for making API calls
• License access to the API
• Rate limit the number of requests
• Control availability of certain features within the API
1.3 GET THE AUTHORIZATION KEYS
To get the keys:
1. Click Sign Up Free and create an account.
2. Click Applications on the top nav bar.
3. Click Get the Key.
4. In the dialog box, click Copy. (Choose the Testing
keys.)
5. Open up a text editor and paste the key.
1.3 GET THE AUTHORIZATION KEYS
Text editors:
• Sublime Text (Mac or PC)
• TextWrangler (Mac)
• WebStorm (Mac or PC)
• Notepad++ (PC)
1.4 MAKE A CURL CALL
Prepare the cURL call:
1. Go into Weather API.
2. Copy the cURL request example for the aqi endpoint into your text editor.
3. Important: If you're on Windows, change the single quotes to double, and add -k as well to work around security certificate issues.
4. Swap in your own API key.
5. Use Google Maps to find the latitude and longtitude of your current location.
1.4 MAKE A CURL CALL
Make the call in cURL (Mac)
1. Open a terminal.
2. Paste the call you have in your text editor into the command line.
3. Press your Enter key.
1.4 MAKE A CURL CALL
Make the call in cURL (Windows)
1. Copy the cURL call from your text editor.
2. Go to Start and type cmd to open up the command line.
3. Right-click and then select Paste to insert the call.
• cURL is a cross-platform way to show requests and responses
• REST APIs follow the same request/return model of the web
• Try using cURL to GET a web page:
curl http://example.com
1.5 UNDERSTANDING CURL
Requests and responses include headers too
Use –i or -I include the response header:
curl http://example.com -i
curl http://example.com -I
1.5 UNDERSTANDING CURL
Other methods you can use besides GET:
• POST: Create a resource
• GET: Read a resource
• PUT: Update a resource
• DELETE: Delete a resource
1.5 UNDERSTANDING CURL
1.5 UNDERSTANDING CURL
Specifying the method with a cURL call
--get
-X GET
-x PUT
curl –X GET http://example.com
1.5 UNDERSTANDING CURL
Passing headers into the request:
-H
curl --get --include 'https://simple-weather.p.mashape.com/aqi?lat=37.354108&lng=-121.955236’ \-H 'X-Mashape-Key: WOyzMuE8c9mshcofZaBke3kw7lMtp1HjVGAjsndqIPbU9n2eET' \-H 'Accept: text/plain'
1.5 UNDERSTANDING CURL
Passing data into the request:
-d
curl -i -H "Accept: application/json" -X POST -d "{status:MIA}" http://personsreport.com?status
1.5 UNDERSTANDING CURL
Make cURL more readable:
curl -i \ -H "Accept: application/json" \ -X POST \ -d "{status:MIA}" \ http://personsreport.com?status \
1.5 UNDERSTANDING CURL
Query strings:
?lat=37.354108&lng=-121.955236
Listening multiple parameters:
¶meter1¶meter2¶meter3
1.6 SUBMIT REST CALLS THROUGH POSTMAN
GUI clients make REST calls a little easier
Common GUI clients:
• Postman• Advanced REST Client• Paw
1.6 SUBMIT REST CALLS THROUGH POSTMAN
Insert the cURL call into Postman following the sample screenshot
1.7 ANALYZE THE JSON RESPONSE
Prettify the JSON response: http://jsonformatter.curiousconcept.com/
JSON is how most REST APIs structure the response
1.7 ANALYZE THE JSON RESPONSE
JSON objects are key-value pairs:
{"key1":"value1","key2":"value2"}
JSON objects start and end with curly braces { }.
1.7 ANALYZE THE JSON RESPONSE
JSON arrays are lists of items:
["first", "second", "third"]
Arrays start and end with square brackets [ ].
1.7 ANALYZE THE JSON RESPONSE
An array can contain a list of objects:
[ { "name":"Tom", "age":39 }, { "name":"Shannon", "age":37 }]
1.7 ANALYZE THE JSON RESPONSE
An object can contain arrays:
children: ["Avery","Callie","lucy","Molly"],hobbies: ["swimming","biking","drawing","horseplaying"]
1.7 ANALYZE THE JSON RESPONSE
Identify the objects and arrays in the weatherdata API response.
• Where are the objects?
• Where are the arrays?
1.8 LOG THE JSON RESPONSE TO THE CONSOLE
Making use of the JSON response
Use the sample code from Mashape to parse and display the REST response: http://docs.mashape.com/javascript
1.8 LOG THE JSON RESPONSE TO THE CONSOLE
Customize the Mashape code with the weatherdata endpoint:
1. Open text editor. Insert Mashape code.
2. Customize the url to the useweatherdata endpoint.
3. Enter your API key.
4. Uncomment out the \\ next to console.log(data).
5. Save and view the file in Chrome.
6. Open the Developer Console: View > Developer > JavaScript Console. Refresh page.
1.8 LOG THE JSON RESPONSE TO THE CONSOLE
You can customize your Console log messages
Inspect the payload
Replace "undefined”:
document.getElementById("output").innerHTML = data.query.results.channel.item.description;
1.9 ACCESS THE VALUES FROM JSON
Dot notation allows you to access specific values from the JSON response
data.query.results.channel.item.description
1.9 ACCESS THE VALUES FROM JSON
How dot notation works
"data": {"name": "Tom"}
To access Tom, I would use data.name.
1.9 ACCESS THE VALUES FROM JSON
Use square brackets to access the values in an array:
"data" : {"items": ["ball", "bat", "glove"]}
To access glove, you would use data.items[2]
1.9 ACCESS THE VALUES FROM JSON
Download the dotnotationexercise.html file from the workshop files.
Change john.children[0].child1 to display the following:
• green
• nike
• goldenrod
• Sarah
1.9 ACCESS THE VALUES FROM JSON
Get the wind speed from the weather API weatherdata endpoint.
Download the windcalls.html file from the workshop files. Look at the different values accessed from the JSON response.
2.0 YOU HAVE A NEW API TO DOCUMENT
Shift perspectives: Now you're the technical writer
You have a new endpoint to document
Review the wiki page: http://idratherbewriting.com/restapicourse2-0/
2.0 YOU HAVE A NEW API TO DOCUMENT
Essential sections in REST API documentation:
• Resource description
• Endpoint
• Methods
• Parameters
• Request submission example
• Request response example
• Status and error codes
• Code samples
2.0 YOU HAVE A NEW API TO DOCUMENT
Create the basic structure for the endpoint documentation
Use a text editor to create the sections.
Bonus: Use Markdown syntax.
2.1 DOCUMENTING THE RESOURCE DESCRIPTION
The terminology to describe a "resource" varies: • API calls• Endpoints• API methods• Calls• Resources• Objects• Services• Requests
2.1 DOCUMENTING THE RESOURCE DESCRIPTION
Look at some examples:
• Mailchimp• Twitter• Instagram
2.1 DOCUMENTING THE RESOURCE DESCRIPTION
Referring to resources by the endpoint name can get problematic:api_site.com/{apikey}/users// gets all users
api_site.com/{apikey}/users/{userId}// gets a specific user
api_site.com/{apikey}/rewards// gets all rewards
api_site.com/{apikey}/rewards/{rewardId}// gets a specific reward
api_site.com/{apikey}/users/{userId}/rewards// gets all rewards for a specific user
api_site.com/{apikey}/users/{userId}/rewards/{rewardId}// gets a specific reward for a specific user
api_site.com/{apikey}/users/{userId}/rewards/{missionId}// gets the rewards for a specfic mission related to a specific user
api_site.com/{apikey}/missions/{missionid}/rewards// gets the rewards available for a specific mission
2.1 DOCUMENTING THE RESOURCE DESCRIPTION
When describing the resource, start with a verb.
Review some examples:
• Delicious API• Foursquare API• Box API
2.1 DOCUMENTING THE RESOURCE DESCRIPTION
Review the surf report wiki page (2.0) containing the information about the endpoint, and try to describe the endpoint in the length of one or two sentences.
2.1 DOCUMENTING THE RESOURCE DESCRIPTION
• Critique the Mashape Weather API descriptions
• There’s a difference between reference docs versus user guides
• Re-using the resource description
2.2 DOCUMENTING THE ENDPOINT DEF. AND METHOD
Terminology for the endpoint definition varies:• Requests• Endpoints• API methods• Resource URIs• Resource URLs• URLs• URL syntax
2.2 DOCUMENTING THE ENDPOINT DEF. AND METHOD
The endpoint definition usually contains the end path only
/surfreport/{beachId}
Represent parameter values with curly braces
2.2 DOCUMENTING THE ENDPOINT DEF. AND METHOD
• Write the endpoint definition for surfreport
• Aim for 1-3 sentences
2.3 DOCUMENTING PARAMETERS
Data types indicate the format for the values:
• String
• Integer
• boolean
2.3 DOCUMENTING PARAMETERS
• Parameter order doesn’t matter
/surfreport/{beachID}?days=3&units=metric&time=1400
• Note any max and min values
• Note whether parameters are optional or required
2.3 DOCUMENTING PARAMETERS
• You can also pass parameters in the JSON body
{"days": 2,"units": "imperial","time": 1433524597}
• Time values usually follow ISO or Unix format
2.4 DOCUMENTING SAMPLE REQUESTS
The sample request clarifies how to use the endpoint
http://api.nytimes.com/svc/search/v2/articlesearch.response-format?[q=search term&fq=filter-field:(filter-term)&additional-params=values]&api-key=####
2.4 DOCUMENTING SAMPLE REQUESTS
• If different requests return different responses, show multiple responses
Document the sample request with the surfreport/{beachId} endpoint
2.5 DOCUMENTING SAMPLE RESPONSES• Provide a sample response for the endpoint
• Example from Flattr API
• Define what the values mean in the endpoint response
2.5 DOCUMENTING SAMPLE RESPONSES
Strategies for documenting nested objects
Check out the following approaches:
• Dropbox• Bit.ly• eBay
2.5 DOCUMENTING SAMPLE RESPONSES
Information design choice: Where to include the response
2.5 DOCUMENTING SAMPLE RESPONSES
• Use realistic values in the response
• Format the JSON in a readable way
• Add syntax highlighting
• Some APIs embed dynamic responses
2.5 DOCUMENTING SAMPLE RESPONSES
Create a section for a sample request in your surfreport/{beachId} endpoint
2.6 DOCUMENTING RESPONSE AND ERROR CODES
• Response codes let you know the status of the request
• Common status codes follow standard protocols: http://www.restapitutorial.com/httpstatuscodes.html
2.6 DOCUMENTING RESPONSE AND ERROR CODES
• List the HTTP response and error codes
• Main page and also on each endpoint where relevant
2.6 DOCUMENTING RESPONSE AND ERROR CODES
Run your request and look at your header code
List three status codes for surfreport/{beachId}
2.7 DOCUMENTING CODE SAMPLES IN REST APIS
• Code samples bridge the gap between reference and user guides
• Look at the code sample on Mashape: http://docs.mashape.com/javascript
• Code samples are like candy for developers
2.7 DOCUMENTING CODE SAMPLES IN REST APIS
• You are not the audience
• Focus on the why, not the what
• Focus on the why, not the what
• Focus your explanation on your company's code only
2.7 DOCUMENTING CODE SAMPLES IN REST APIS
• Keep code samples simple
• Add both code comments and before-and-after explanations
• Make code samples copy-and-pastable
2.7 DOCUMENTING CODE SAMPLES IN REST APIS
Provide a code sample in your target language
2.7 DOCUMENTING CODE SAMPLES IN REST APIS
• From code samples to real tasks in user guides
• Your turn to practice: Create a code sample and documentation for the surfreport endpoint
2.8 PUTTING IT ALL TOGETHER
• View my sample here: http://idratherbewriting.com/restapicourse2-8/
• Share and comment on each other’s samples?
2.9 CREATING THE USER GUIDE
User guides versus reference documentation
Essential sections in a user guide:
• Overview• Getting started• Authorization keys• Core concepts• Rate limits• Code samples• Hello world tutorial• Quick reference• Glossary
3.0 COMPLETION
Learning summary
• How to make calls to an API using cURL and Postman
• How to pass parameters to API calls
• How to inspect the objects in the JSON payload
• How to use dot notation to access the JSON values you want
• How to display the integrate the information into your site
3.0 COMPLETION
Learning summary
• Documenting the resource description
• Documenting the endpoint definition and method
• Documenting parameters
• Documenting the request example
• Documenting the response example
• Providing a code example
• Listing status codes
IMAGE CREDITSMost images are screenshots linked to a webpage, but some are from Flickr. Required attribution is as follows:
• Structure, https://flic.kr/p/oFD6MM Rafal Zych
• Earth patterns. https://flic.kr/p/ssQqiL Evriel Venefice
• Dave’s Bike Tools, https://flic.kr/p/QMVMw Bri Pettis