This document captures GSA's recommended best practices, conventions, and standards for Application Programming Interfaces (APIs). Projects should start by addressing API Security, followed by implementing the Mandatory Items and Mandatory For New Public APIs. After addressing those, review Other Considerations for additional advice.
These standards are forked from the 18F API Standards. They are also influenced by several other sources, including the White House API Standards and best practices from the private sector.
These standards are intended to streamline the process for GSA organizations to publish new APIs by providing practical and pragmatic advice. We believe these standards will benefit GSA API development and provide consistency.
Most of the content in these standards relates to "RESTful" APIs. However, many of the standards are equally appropriate for other types of web service.
A few specific recommendations are provided for SOAP web services, and we encourage the GSA community to share more recommendations.
Because APIs may be developed with multiple technologies, these standards avoid details internal to the development of the application or unique to a development platform. They generally focus on the "externals" that will be exposed to users.
For the purposes of these standards, we use the following definitions:
API Security is governed by the GSA IT Security Procedural Guide: API Security CIO-IT Security-19-93. Reference that guide for security related topics such as HTTPS encryption, authentication, and authorization.
These are mandatory for GSA public APIs, with exceptions where noted.
(Public APIs) A directory of GSA public APIs is available at open.gsa.gov/api. Add your API to this directory by posting an issue or pull request in the GitHub repository.
Part of this process is to first complete the neccessary steps to add your GitHub Account to the GSA Organization and then send an email to the CTO team to have your account added to the open-gsa-redesign User Group. The steps are documented on the Adding API Documentation GitHub page.
(Public APIs) The api.data.gov service is an API management service for federal agencies. GSA APIs should use the api.gsa.gov
base domain with this service. By having the api.gsa.gov
base URL as a proxy to developers, this also makes it easier to update and maintain the API in the future since you can update the underlying system and URLs without exposing it to the public. In some cases, other specific base domains can be established with this service for GSA APIs.
Initially, this service can be added as a new version of the URL, and then existing users can be transitioned to the new URL. For help setting this up, contact the api.data.gov team at api.data.gov@gsa.gov.
The api.gsa.gov service also provides:
Keys managed by api.data.gov can be re-used with other APIs hosted by this service, which reduces complexity for users. This service also allows the use of a DEMO_KEY for unauthenticated access, without keys, which reduces the "Time To First Hello World" for developers using your API.
Exceptions: Not required for SOAP APIs. However, it may still provide value to your SOAP API.
All APIs must support versioning. The recommended method of versioning REST APIs is to include a major version number in the URL path. For example "/v1/". An example of this method can be found at: https://gsa.github.io/sam_api/sam/versioning.html.
Major versions (e.g. v1, v2) should be reserved for breaking changes and major releases. Minor versions (eg. 1.1, 2.3) are not required, but can provide additional information about the API. If used, they should not be in the URL, but should be in the HTTP Headers.
Any changes made to a specific version of your API should not break your contract with existing users. If you need to make a change that will break that contract, create a new major version.
Examples of Breaking Changes for REST APIs:
Examples of Breaking Changes for SOAP web services:
It is not necessary to increment the major API version for non-breaking changes. Non-breaking changes can be reflected in a minor version, if used.
Examples of Non-Breaking Changes for REST APIs:
Examples of Non-Breaking Changes for SOAP web services:
Leave at least one previous major version intact. And communicate to existing users to understand when previous versions will be decommissioned.
Use "/v0/" to represent an API that is in prototype or alpha phase and is likely to change frequently without warning.
The developer's entry point to your API will likely be the documentation that you provide.
Your API documentation should provide:
Additional nice-to-haves include:
Have an obvious mechanism for clients to report issues and ask questions about the API. It is critical to respond to issues posted or queries submitted by developers. This demonstrates that the API can be counted on for production usage. If an immediate fix (or even a developer to investigate) is not readily available, respond anyway. Developers will be glad to know when you'll be able to take a look.
When using GitHub for an API's code or documentation, use the associated issue tracker. In addition, publish an email address for direct, non-public inquiries.
If you don't have a support channel specific to your API, you can use the issue tracker at GSA-APIs. Be sure your support team subscribes to issues there.
For REST APIs, The API documentation should provide a clear link to the API's OpenAPI Specification file. This specification was formerly known as the Swagger specification. This specification file can be used by development or testing tools accessing your API.
Using Version 2.0 or later of the specification is recommended. Information about versions can be found here: OpenAPI Specification Revision History.
Exceptions: Not required for SOAP APIs.
For REST APIs, An "endpoint" is a combination of two things:
GET
, POST
, PUT
, PATCH
, DELETE
)/articles
)The URL path should follow this pattern for a collection of items:
(base domain)/{business_function}/{application_name}/{major version}/{plural_noun}
An example would be:
https://api.gsa.gov/financial_management/sample_app/v1/vendors
The URL path for an individual item in this collection would default to:
(base domain)/{business_function}/{application_name}/{major version}/{plural_noun}/{identifier}
An example would be:
https://api.gsa.gov/financial_management/sample_app/v1/vendors/123
Exceptions: Not required for SOAP APIs. Not required for APIs that were in progress or production prior to December 2018.
When you have an OpenAPI specification file (mandatory for public APIs), there are tools that can use this specification file to automatically generate a page where your users can try out your API without too much effort. Swagger UI is one such tool; here is an example.
We strongly recommend implementing this item, as it provides a significant enhancement to developer experience and helps ensure proper use of your API. Swagger UI can be implemented on any website, even a static site, with the inclusion of a few JavaScript and CSS files.
See the Swagger UI project for installation and configuration instructions.
After downloading Swagger UI, you generally will want a page that loads the Swagger UI and your OpenAPI specification file:
<!-- in the HEAD of the page -->
<link rel="stylesheet" type="text/css" href="https://github.com/GSA/api-standards/blob/master/swagger-ui.css" >
<!-- in the BODY of the page -->
<div id="swagger-ui"></div>
<script src="https://github.com/GSA/api-standards/raw/master/swagger-ui-bundle.js"></script>
<script src="https://github.com/GSA/api-standards/raw/master/swagger-ui-standalone-preset.js"></script>
<script>
window.onload = function() {
// openapi.yaml is your OpenAPI specification file (can also be a JSON file)
const ui = SwaggerUIBundle({
url: "openapi.yaml",
dom_id: '#swagger-ui',
presets: [
SwaggerUIBundle.presets.apis,
SwaggerUIBundle.SwaggerUIStandalonePreset,
],
layout: "StandaloneLayout"
})
window.ui = ui
}
</script>
Depending on your site, the above is roughly all you need to generate the API testing tool.
If details of API need to be secured from public viewing, the API documentation can be on a web page that is only accessible to authorized users of the API. This protected documentation may be mentioned on a separate public page, or directly linked from the API Directory.
Your API documentation should provide:
Additional nice-to-haves include:
On the public or protected documentation page, include a method for users to report issues and ask questions about the API. It is critical to respond to issues posted or queries submitted by developers. This demonstrates that the API can be counted on for production usage. If an immediate fix (or even a developer to investigate) is not readily available, respond anyway. Developers will be glad to know when you'll be able to take a look.
The following items will be beneficial to the users of your APIs. (Full details of these items are linked to the previous section of this document.)
Add Your API To The GSA API Directory Use The api.data.gov Service Provide Support For Versioning Provide An OpenAPI Specification File Follow the Standard API Endpoint Design
For APIs that syndicate data, consider several common client use cases:
The best way to understand and address the weaknesses in an API's design and implementation is to use it in a production system.
Whenever feasible, design an API in parallel with an accompanying integration of that API.
A few methods to accomplish this include:
Consider developers who will be using your APIs. Their path to using your API will include discovery and initial investigation, sample API calls, development and testing, deployment and production usage. Consider each of these functions in your documentation, support, and change notification process. Consider performing formal API Usability Testing to understand the developer experience in using your API. More information about this type of testing is available here: API Usability Testing.
Have a simple mechanism for clients to follow changes to the API.
Common ways to do this include a mailing list or a persistent issue in the GitHub repository that users can subscribe to. For example: Notification Thread: Updates to GSA APIs
If an API can no longer be supported, consider decommissioning the API and removing the documentation. If the API will remain available for historical purposes without support, update the documentation to reflect this.
If an API is going to be decommissioned, retired, or changed in such a way that current users will be impacted, it is critical that those users be notified in advance so that they can prepare for the change instead of experiencing an unexpected interruption. The most common situations where this happens is if an API is going to be decommissioned or if an update to the API will change how the API functions (note that this is where Versioning is important). If these users aren't notified, their application that consumes the API may break and they may suffer significant consequences from their application's resulting downtime. Furthermore, experiencing this may seriously degrade the trust that the developer has in GSA's API programs and may cause them to avoid our services going forward if they feel that they cannot rely on them.
In addition to updating the API documentation in advance with a highly visible notice, it is important to use API analytics to see which API keys have consumed the service in recent months. You can then use the email addresses associated with each key to send (preferably more than one) notification of the upcoming change. Note that posting a notice on the API documentation is not sufficient by itself, as many current users will not necessarily revisit the documentatation. Proactive notification of recent users is essential.
JSON is an excellent, widely supported transport format, suitable for many web APIs.
Supporting JSON and only JSON is a practical default for APIs, and generally reduces complexity for both the API provider and consumer.
General JSON guidelines:
under_score
or CamelCase
for your API keys, make sure you are consistent.And specifically, use ISO 8601, in UTC.
For just dates, that looks like 2013-02-27
. For full times, that's of the form 2013-02-27T10:00:00Z
.
This date format is used all over the web, and puts each field in consistent order -- from least granular to most granular.
The following are recommended HTTP Response Codes that API should return. They are based on the OWASP REST Security Cheat Sheet from December 2018.
Return Code | Message | Description |
---|---|---|
200 | OK | Response to a successful REST API action. The HTTP method can be GET, POST, PUT, PATCH or DELETE. |
201 | Created | The request has been fulfilled and the resource created. A URL for the created resource is returned in the Location header. |
202 | Accepted | The request has been accepted for processing, but processing is not yet complete |
400 | Bad Request | The request is malformed, such as a message body format error, missing headers, etc. |
401 | Unauthorized | Wrong or no authentication ID/ password provided. |
403 | Forbidden | Used when the authentication succeeded but the authenticated user does not have permission to the requested resource. |
404 | Not Found | When a non-existent resource is requested. |
406 | Unacceptable | The client presented a content type in the Accept header which is not supported by the server API. |
405 | Method Not Allowed | The error for an unexpected HTTP method. For example, the REST API is expecting HTTP GET, but HTTP PUT is used. |
413 | Payload Too Large | Used to signal that the request size exceeded the given limit (e.g. regarding file uploads and to ensure that the requests have reasonable sizes). |
415 | Unsupported Media Type | The requested content type is not supported by the REST service. This is especially effective when you are working primary with JSON or XML media types. |
429 | Too Many Requests | The error is used when there may be a DOS attack detected or the request is rejected due to rate limiting. |
500 | Internal Server Error | An unexpected condition prevented the server from fulfilling the request. Be aware that the response should not reveal internal information that helps an attacker, e.g. detailed error messages or stack traces. |
501 | Not Implemented | The REST service does not implement the requested operation yet |
502 | Service Unavailable | The REST service is temporarily unable to process the request. Used to inform the client it should retry at a later time. |
Note: GSA APIs should be using the api.data.gov service as a proxy between the client and the API. That service will return additional HTTP codes, prior to the request reaching the base API. Here is a list of those code: https://api.data.gov/docs/errors/
If pagination is required to navigate datasets, use the method that makes the most sense for the API's data.
Common patterns:
page
and per_page
. Intuitive for many use cases. Links to "page 2" may not always contain the same data.offset
and limit
. This standard comes from the SQL database world, and is a good option when you need stable permalinks to result sets.since
and limit
. Get everything "since" some ID or timestamp. Useful when it's a priority to let clients efficiently stay "in sync" with data. Generally requires result set order to be very stable.Include enough metadata so that clients can calculate how much data there is, and how and whether to fetch the next set of results.
Example of how that might be implemented:
{
"results": [ ... actual results ... ],
"pagination": {
"count": 2340,
"page": 4,
"per_page": 20
}
}
Just use UTF-8.
Handle accented characters or "smart quotes" in API output, even if they're not expected.
An API should tell clients to expect UTF-8 by including a charset notation in the Content-Type
header for responses.
An API that returns JSON should use:
Content-Type: application/json; charset=utf-8
For clients to be able to use an API from inside web browsers, the API must enable Cross-Original Resource Sharing (CORS).
For the simplest and most common use case, where the entire API should be accessible from inside the browser, enabling CORS is as simple as including this HTTP header in all responses:
Access-Control-Allow-Origin: *
It's supported by every modern browser, and will Just Work in many JavaScript clients.
For additional guidance on CORS, see the GSA IT Security Procedural Guide: API Security CIO-IT Security-19-93.
At its most basic level, API testing is intended to reveal bugs: inconsistencies or deviations from the expected behavior. Continuous testing is also very important to make sure it continues to work when the public has access to it. The risk of putting a bad, and potentially insecure, product on the market is greater than the cost to test it.
Types of API Testing
Provide a WSDL.
Most platforms will provide this by default out of the box. Leave it active unless you have a strong reason not to. A useful convention is that the WSDL will be available at: {URL Path)?wsdl
Provide documentation for SOAP web services.
Users of SOAP web services need documentation, just like REST users.
See examples of versioning of SOAP web services above.
Several additional API related topics continue to emerge and will be considered for future updates to these standards.
That list includes:
If you see a future topic we need to consider, take a look at our contributing page for instructions to share that info.