• This repository has been archived on 17/Dec/2021
  • Stars
    star
    488
  • Rank 90,182 (Top 2 %)
  • Language
  • License
    Other
  • Created over 10 years ago
  • Updated about 4 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

API Standards for 18F

18F API Standards

18F is a technology team inside the US federal government. 18F is very API-focused: our first project was an API for business opportunities.

This document captures 18F's view of API best practices and standards. We aim to incorporate as many of them as possible into our work.

APIs, like other web applications, vary greatly in implementation and design, depending on the situation and the problem the application is solving.

This document provides a mix of:

  • High level design guidance that individual APIs interpret to meet their needs.
  • Low level web practices that most modern HTTP APIs use.

Design for common use cases

For APIs that syndicate data, consider several common client use cases:

  • Bulk data. Clients often wish to establish their own copy of the API's dataset in its entirety. For example, someone might like to build their own search engine on top of the dataset, using different parameters and technology than the "official" API allows. If the API can't easily act as a bulk data provider, provide a separate mechanism for acquiring the backing dataset in bulk.
  • Staying up to date. Especially for large datasets, clients may want to keep their dataset up to date without downloading the data set after every change. If this is a use case for the API, prioritize it in the design.
  • Driving expensive actions. What would happen if a client wanted to automatically send text messages to thousands of people or light up the side of a skyscraper every time a new record appears? Consider whether the API's records will always be in a reliable unchanging order, and whether they tend to appear in clumps or in a steady stream. Generally speaking, consider the "entropy" an API client would experience.

Using one's own API

The #1 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.

Point of contact

Have an obvious mechanism for clients to report issues and ask questions about the API.

When using GitHub for an API's code, use the associated issue tracker. In addition, publish an email address for direct, non-public inquiries.

Notifications of updates

Have a simple mechanism for clients to follow changes to the API.

Common ways to do this include a mailing list, or a dedicated developer blog with an RSS feed.

API Endpoints

An "endpoint" is a combination of two things:

  • The verb (e.g. GET or POST)
  • The URL path (e.g. /articles)

Information can be passed to an endpoint in either of two ways:

  • The URL query string (e.g. ?year=2014)
  • HTTP headers (e.g. X-Api-Key: my-key)

When people say "RESTful" nowadays, they really mean designing simple, intuitive endpoints that represent unique functions in the API.

Generally speaking:

  • Avoid single-endpoint APIs. Don't jam multiple operations into the same endpoint with the same HTTP verb.
  • Prioritize simplicity. It should be easy to guess what an endpoint does by looking at the URL and HTTP verb, without needing to see a query string.
  • Endpoint URLs should advertise resources, and avoid verbs.

Some examples of these principles in action:

Just use JSON

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:

  • Responses should be a JSON object (not an array). Using an array to return results limits the ability to include metadata about results, and limits the API's ability to add additional top-level keys in the future.
  • Don't use unpredictable keys. Parsing a JSON response where keys are unpredictable (e.g. derived from data) is difficult, and adds friction for clients.
  • Use consistent case for keys. Whether you use under_score or CamelCase for your API keys, make sure you are consistent.

Use a consistent date format

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.

API Keys

These standards do not take a position on whether or not to use API keys.

But if keys are used to manage and authenticate API access, the API should allow some sort of unauthenticated access, without keys.

This allows newcomers to use and experiment with the API in demo environments and with simple curl/wget/etc. requests.

Consider whether one of your product goals is to allow a certain level of normal production use of the API without enforcing advanced registration by clients.

Error handling

Handle all errors (including otherwise uncaught exceptions) and return a data structure in the same format as the rest of the API.

For example, a JSON API might provide the following when an uncaught exception occurs:

{
  "message": "Description of the error.",
  "exception": "[detailed stacktrace]"
}

HTTP responses with error details should use a 4XX status code to indicate a client-side failure (such as invalid authorization, or an invalid parameter), and a 5XX status code to indicate server-side failure (such as an uncaught exception).

Pagination

If pagination is required to navigate datasets, use the method that makes the most sense for the API's data.

Parameters

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.

Metadata

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
  }
}

Always use HTTPS

Any new API should use and require HTTPS encryption (using TLS/SSL). HTTPS provides:

  • Security. The contents of the request are encrypted across the Internet.
  • Authenticity. A stronger guarantee that a client is communicating with the real API.
  • Privacy. Enhanced privacy for apps and users using the API. HTTP headers and query string parameters (among other things) will be encrypted.
  • Compatibility. Broader client-side compatibility. For CORS requests to the API to work on HTTPS websites -- to not be blocked as mixed content -- those requests must be over HTTPS.

HTTPS should be configured using modern best practices, including ciphers that support forward secrecy, and HTTP Strict Transport Security. This is not exhaustive: use tools like SSL Labs to evaluate an API's HTTPS configuration.

For an existing API that runs over plain HTTP, the first step is to add HTTPS support, and update the documentation to declare it the default, use it in examples, etc.

Then, evaluate the viability of disabling or redirecting plain HTTP requests. See GSA/api.data.gov#34 for a discussion of some of the issues involved with transitioning from HTTP->HTTPS.

Server Name Indication

If you can, use Server Name Indication (SNI) to serve HTTPS requests.

SNI is an extension to TLS, first proposed in 2003, that allows SSL certificates for multiple domains to be served from a single IP address.

Using one IP address to host multiple HTTPS-enabled domains can significantly lower costs and complexity in server hosting and administration. This is especially true as IPv4 addresses become more rare and costly. SNI is a Good Idea, and it is widely supported.

However, some clients and networks still do not properly support SNI. As of this writing, that includes:

  • Internet Explorer 8 and below on Windows XP
  • Android 2.3 (Gingerbread) and below.
  • All versions of Python 2.x (a version of Python 2.x with SNI is planned).
  • Some enterprise network environments have been configured in some custom way that disables or interferes with SNI support. One identified network where this is the case: the White House.

When implementing SSL support for an API, evaluate whether SNI support makes sense for the audience it serves.

Use UTF-8

Just use UTF-8.

Expect 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

CORS

For clients to be able to use an API from inside web browsers, the API must enable 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, like jQuery.

For more advanced configuration, see the W3C spec or Mozilla's guide.

What about JSONP?

JSONP is not secure or performant. If IE8 or IE9 must be supported, use Microsoft's XDomainRequest object instead of JSONP. There are libraries to help with this.

Public domain

This project is in the public domain within the United States, and copyright and related rights in the work worldwide are waived through the CC0 1.0 Universal public domain dedication.

All contributions to this project will be released under the CC0 dedication. By submitting a pull request, you are agreeing to comply with this waiver of copyright interest.

More Repositories

1

development-guide

A set of guidelines and best practices for an awesome software engineering team
HTML
1,159
star
2

analytics.usa.gov

The US federal government's web traffic.
SCSS
693
star
3

analytics-reporter

Lightweight analytics reporting and publishing tool for Google Analytics data.
JavaScript
616
star
4

technology-budgeting

See https://derisking-guide.18f.gov/
492
star
5

identity-idp

Login.gov Core App: Identity Provider (IdP)
Ruby
476
star
6

domain-scan

A lightweight pipeline, locally or in Lambda, for scanning things like HTTPS, third party service use, and web accessibility.
Python
369
star
7

checklistomania

Centrally managed todo lists for complex processes - onboarding, offboarding, management changes, etc.
JavaScript
364
star
8

accessibility

A repo to organize the guidelines and best practices for accessibility at 18f.
HTML
328
star
9

rdbms-subsetter

Generates a subset of a relational database that respects foreign key constraints
Python
317
star
10

laptop

DEPRECATED: A shell script which turns your Mac into an awesome web development machine.
Shell
317
star
11

open-source-guide

18F’s Style guide for open source project documentation
Ruby
290
star
12

18f.gsa.gov

This repository contains 18F's website.
HTML
289
star
13

methods

The methods 18F uses to practice human-centered design.
SCSS
221
star
14

jekyll-get

DEPRECATED - see https://github.com/brockfanning/jekyll-get-json instead
Ruby
212
star
15

open-data-maker

make it easy to turn a lot of potentially large csv files into easily accessible open data
Ruby
201
star
16

ads-bpa

A guide for the Agile Delivery Services BPA
Ruby
193
star
17

dolores-landingham-slack-bot

A Slack bot to welcome new 18F hires with the authority and compassion of Mrs. Landingham
Ruby
189
star
18

API-All-the-X

Resources and Materials for the /Developer Program
CSS
167
star
19

https

(Deprecated) https guidance for the 18F team
158
star
20

uswds-jekyll

A Jekyll theme showcasing the U.S. Web Design System
JavaScript
132
star
21

docker-compose-django-react

A strawman set up for using both Django and React in a new app
JavaScript
128
star
22

frontend

18F's Front End Guild –  content has been moved to https://github.com/18F/development-guide
Ruby
122
star
23

tock

We use Tock to track and report our time at 18F
Python
120
star
24

handbook

The home of policies and guidelines that make up TTS.
HTML
115
star
25

C2

an approval process automation tool
Ruby
104
star
26

fbopen

[DEPRECATED] An open API server, data import tools, and sample apps to help small businesses search for opportunities to work with the U.S. government.
JavaScript
101
star
27

pulse

How the federal .gov domain space is doing at best practices and policies.
CSS
94
star
28

standup-slack-bot

A Slack bot to streamline team standup without disturbing the overall flow of conversation
JavaScript
87
star
29

api.data.gov

A hosted, shared-service that provides an API key, analytics, and proxy solution for government web services.
HTML
84
star
30

content-guide

18F Content Guide
HTML
79
star
31

ux-guide

Resources, norms, and practices for doing user experience research and design work at 18F.
HTML
76
star
32

crime-data-explorer

Moved to https://github.com/fbi-cde
69
star
33

micropurchase

18F's micro-purchase threshold experiment management app.
Ruby
68
star
34

pages

DEPRECATED: Publishing platform for 18F sites a la GitHub pages
Ruby
63
star
35

transformation-research

Best practices in government digital transformation
60
star
36

doc_processing_toolkit

Python library to extract text from PDF, and default to OCR when text extraction fails.
Python
55
star
37

automated-testing-playbook

A set of principles, practices, idioms, and strategies pertaining to automated software testing and its adoption
Ruby
52
star
38

eligibility-rules-service

Researching an eligibility rules service - project documentation and task management
51
star
39

2015-foia

Please check out https://github.com/18F/foia-hub/issues to track our work. This repo is for project wide discussion, blogging, and scratch space for 18F's FOIA modernization team.
Python
50
star
40

us-federal-holidays

A Node.js package for getting US federal holidays for a given year, or determining if a date is a federal holiday.
JavaScript
49
star
41

guides-template

Jekyll template for 18F Guides, based on CFPB/DOCter
Ruby
49
star
42

2015-foia-hub

A consolidated FOIA request hub.
CSS
47
star
43

glossary

A glossary panel for your site to help readers understand jargon
JavaScript
46
star
44

agile

Agile Principles and Practice, documented by the 18F Agile Guild
HTML
46
star
45

lean-product-design

A guide to using Lean Product Design on your project
Ruby
46
star
46

hub

DEPRECATED: Documentation hub for the 18F team
JavaScript
46
star
47

web-design-standards-drupal

A Drupal base theme that uses the U.S. Web Design System. (ARCHIVED)
CSS
46
star
48

dashboard

DEPRECATED: A site to track our projects' status and much, much more...
JavaScript
44
star
49

autoapi

A basic spreadsheet to api engine
Python
43
star
50

eng-hiring

18F Engineering's guide to candidate selection, from resume screen to offer.
HTML
43
star
51

jekyll_pages_api

a Jekyll Plugin that generates a JSON file with data for all the Pages in your Site
Ruby
43
star
52

myusa

MyUSA was a single sign-on project for government, now deprecated. (More info: https://18f.gsa.gov/2015/05/18/myusa/)
Ruby
43
star
53

dns

DNS configuration for domains managed by GSA TTS
HCL
42
star
54

pdf-forms-tutorial

A step-by-step guide for programatically filling out PDF forms
Java
41
star
55

jekyll_pages_api_search

DEPRECATED - Jekyll search plugin based on lunr.js and jekyll_pages_api
Ruby
40
star
56

before-you-ship

merged into the TTS Handbook
Ruby
38
star
57

piipan

A privacy-preserving system for storing and matching de-identified Personal Identifiable Information (PII) records.
C#
37
star
58

stylelint-rules

A style (CSS, Sass) linter for the 18F style guide
JavaScript
36
star
59

joining-18f

A guide for anyone interested in joining the 18F team
CSS
36
star
60

charlie

18F's Slack bot, Charlie. Built on Bolt
JavaScript
35
star
61

identity-site

This is the Login.gov main website where the public is able to learn about their one account for government.
HTML
34
star
62

ReVAL

ReVAL: Reusable Validation Library - A Django App for validating data via API and web interface
Python
32
star
63

product-guide

A handbook for the 18F product team and to promote our product management best practices.
HTML
32
star
64

compliance-toolkit

Compliance at the speed of Delivery.
31
star
65

continua11y

continuous integration for website accessibility
JavaScript
31
star
66

fedramp-data

A repository for the data underlying the FedRamp Dashboard
JavaScript
31
star
67

emoji_search

A super simple commandline utility to search for slack messages that have been reacted to with a specific emoji
Python
31
star
68

slides

Slides for 18F - built automatically using Federalist
HTML
30
star
69

about_yml

.about.yml project metadata schema and tools
Ruby
30
star
70

identity-dev-docs

Login.gov developer documentation
HTML
29
star
71

raktabija

Bootstrap AWS account with Terraform and Go.CD
Python
29
star
72

confidential-survey

A Rails app for conducting confidential surveys without violating user privacy
Ruby
29
star
73

javascript-lessons

Beginning and Advanced lessons in javascript with a focus on functional programming. This repo contains both exercises and solutions. It is used by 18F to train its internal staff, but of course anyone is welcome to use it and possibly contribute.
JavaScript
29
star
74

jekyll_frontmatter_tests

A Jekyll plugin to test frontmatter on posts and other documents in a Jekyll site.
Ruby
28
star
75

data-federation-project

A project focused on tools and best practices to supported federated data collection efforts
28
star
76

tech-talks

Suggestions, schedules, and other information about the Engineering Chapter's Tech Talk meetings.
Jupyter Notebook
28
star
77

ifgovthenthat

If Gov Then That website, a project to promote gov open data by designing clever uses for government APIs. (Currently on hold.)
CSS
27
star
78

foia-recommendations

National FOIA Project: Research and Recommendations
HTML
27
star
79

brand

18F Brand
SCSS
26
star
80

onboarding-documents

Forms, emails, and checklists to help with onboarding
26
star
81

18f-scaffolding

A scaffold/generator to standardize 18F project setup
Shell
26
star
82

bpa-fedramp-dashboard

FedRAMP Dashboard BPA Order
25
star
83

culper

Culper is the foundation for eApp, a part of the National Background Investigation System (NBIS), supporting the SF-86, SF-85, and SF-85P. This is its source code and developer documentation. For background information and a demo video see https://github.com/18F/culper/wiki
JavaScript
25
star
84

vulnerability-disclosure-policy

The vulnerability disclosure policy for 18F and GSA's Technology Transformation Service.
25
star
85

code-of-conduct

18F's code of conduct.
24
star
86

scrapebox

A simple, system independent infrastructure for performing web scraping. Utilizes Vagrant virtualbox interface and puppet provisioning to create and execute scraping of web content to structured data quickly and easily without modifying your core system.
Python
24
star
87

identity-oidc-sinatra

Example OpenID Connect relying party as a Sinatra app
Ruby
23
star
88

identity-design-system

An extension of the U.S. Web Design System used on Login.gov sites to consistently identify the Login.gov brand.
SCSS
22
star
89

elasticsearch-rails-ha-gem

high availability extensions to the Elasticsearch::Rails standard tasks
Ruby
21
star
90

html-proofer-docker

HTML validation, made easy
Shell
21
star
91

fedramp-dashboard

JavaScript
21
star
92

tts-tech-portfolio

Home of the TTS Technology Portfolio team
JavaScript
21
star
93

linkify-citations

Turns legal citations in the DOM into links
HTML
20
star
94

ghad

GitHub administration command line tool
JavaScript
20
star
95

archived-guides

A collection of 18F guides.
HTML
20
star
96

Modular-Contracting-And-Agile-Development

Modular contracting and agile development resources.
CSS
20
star
97

data-act-pilot

This small DATA Act pilot contains code that translates agency data to a uniform DATA act format.
Python
20
star
98

shipper

Continuous deployment made easy and secure
Go
19
star
99

project-artifacts

Resources for running path analysis projects at 18F
19
star
100

urlsize

get the size of one or more URLs
JavaScript
19
star