# Census tract

> POST /census/tract geocodes a US address with the Census Geocoder: coordinates, census tract, block group and block GEOIDs, county, place and districts.

`POST https://api.qelka.com/v1/census/tract`

Geocode a US street address with the Census Geocoder of the US Census Bureau and get its latitude and longitude with every Census geography it falls in: state, county, census tract, block group and block with their GEOIDs, place, county subdivision, congressional and state legislative districts, metro area, ZIP Code Tabulation Area and school district. Each lookup costs 1 credit when the address matches; addresses that do not match, errors and test keys are never billed.

## Request

Send the address on one line: house number, street, city, state and ZIP code when you have it.

| Field | Type | Required | Default | Description |
|---|---|---|---|---|
| `address` | string | Yes | none | A US street address on one line, 5 to 300 characters. |
| `fresh` | boolean | No | `false` | `true` skips the 30-day result cache and asks the Census Geocoder again. |

The Census Geocoder places addresses on streets, so PO boxes, rural routes and streets newer than its address ranges usually return `no_match`. Addresses outside the United States never match.

The call waits for the Census Geocoder, which has a 10-second limit, so every snippet sets a 30-second client timeout.

```bash title="cURL"
curl https://api.qelka.com/v1/census/tract \
  --max-time 30 \
  -H "Authorization: Bearer $QELKA_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"address": "1600 Pennsylvania Ave NW, Washington, DC 20500"}'
```
```javascript title="Node.js"
const response = await fetch('https://api.qelka.com/v1/census/tract', {
  method: 'POST',
  headers: {
    Authorization: `Bearer ${process.env.QELKA_API_KEY}`,
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({ address: '1600 Pennsylvania Ave NW, Washington, DC 20500' }),
  signal: AbortSignal.timeout(30_000),
})
const result = await response.json()
console.log(result)
```
```python title="Python"
import os

import requests

api_key = os.environ["QELKA_API_KEY"]
response = requests.post(
    "https://api.qelka.com/v1/census/tract",
    headers={"Authorization": f"Bearer {api_key}"},
    json={"address": "1600 Pennsylvania Ave NW, Washington, DC 20500"},
    timeout=30,
)
result = response.json()
print(result)
```
```php title="PHP"
<?php
$ch = curl_init('https://api.qelka.com/v1/census/tract');
curl_setopt_array($ch, [
    CURLOPT_POST => true,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => [
        'Authorization: Bearer ' . getenv('QELKA_API_KEY'),
        'Content-Type: application/json',
    ],
    CURLOPT_POSTFIELDS => json_encode(['address' => '1600 Pennsylvania Ave NW, Washington, DC 20500']),
    CURLOPT_TIMEOUT => 30,
]);
$result = json_decode(curl_exec($ch), true);
print_r($result);
```
```go title="Go"
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"net/http"
	"os"
	"time"
)

func main() {
	payload, _ := json.Marshal(map[string]any{"address": "1600 Pennsylvania Ave NW, Washington, DC 20500"})
	request, _ := http.NewRequest(http.MethodPost, "https://api.qelka.com/v1/census/tract", bytes.NewReader(payload))
	request.Header.Set("Authorization", "Bearer "+os.Getenv("QELKA_API_KEY"))
	request.Header.Set("Content-Type", "application/json")

	client := &http.Client{Timeout: 30 * time.Second}
	response, err := client.Do(request)
	if err != nil {
		panic(err)
	}
	defer response.Body.Close()

	var result map[string]any
	if err := json.NewDecoder(response.Body).Decode(&result); err != nil {
		panic(err)
	}
	fmt.Println(result)
}
```
```ruby title="Ruby"
require 'json'
require 'net/http'

uri = URI('https://api.qelka.com/v1/census/tract')
request = Net::HTTP::Post.new(uri)
request['Authorization'] = "Bearer #{ENV.fetch('QELKA_API_KEY')}"
request['Content-Type'] = 'application/json'
request.body = JSON.generate({ address: '1600 Pennsylvania Ave NW, Washington, DC 20500' })

response = Net::HTTP.start(uri.host, uri.port, use_ssl: true, read_timeout: 30) do |http|
  http.request(request)
end
result = JSON.parse(response.body)
puts result
```

## Response

Every valid request gets a `200`. Read `status` first: with `no_match`, every other field is `null`.

| Field | Type | Description |
|---|---|---|
| `id` | string | Identifier of this lookup: `lkp_` followed by 26 characters. |
| `object` | string | Always `census_tract`. |
| `input` | string | The `address` you sent, without surrounding spaces. |
| `status` | string | `matched` or `no_match`. |
| `matched_address` | string or null | The address as the Census Geocoder matched it, in its standard form. Compare it with what you sent. |
| `coordinates` | object or null | `latitude` and `longitude`, numbers in decimal degrees, interpolated along the street segment of the address. |
| `tiger_line` | object or null | The TIGER/Line street segment of the address range: its `id`, and `side`, `L` or `R`, the side of the street, or `null`. |
| `state` | object or null | `fips`, the 2-digit state FIPS code; `code`, the USPS abbreviation; `name`. |
| `county` | object or null | `geoid`, 5 digits: state and county FIPS codes; `name`. |
| `county_subdivision` | object or null | The township, town or census county division: `geoid` and `name`. |
| `place` | object or null | The incorporated place, or else the census designated place: `geoid` and `name`. `null` outside any place. |
| `tract` | object or null | `geoid`, 11 digits: state, county and tract codes; `code`, the 6-digit tract code; `name`, such as `Census Tract 9800`. |
| `block_group` | object or null | `geoid`, 12 digits: the tract GEOID and the block group number; `code`, that number. |
| `block` | object or null | `geoid`, 15 digits: the 2020 Census tabulation block; `code`, the 4-digit block number, whose first digit is the block group. |
| `congressional_district` | object or null | `geoid`: state FIPS and district code; `code`, 2 digits, `00` for an at-large seat and `98` for a non-voting delegate; `name`; `congress`, the Congress the districts are drawn for, such as `120`, or `null`. |
| `state_legislative_upper`, `state_legislative_lower` | object or null | The state senate and state house districts: `geoid` and `name`. `null` where the state has none, such as the lower house in the District of Columbia. |
| `metro_area` | object or null | The metropolitan statistical area, or else the micropolitan one: `geoid`, the CBSA code, and `name`. |
| `zcta` | string or null | The ZIP Code Tabulation Area of the 2020 Census, the Census approximation of the ZIP code area. |
| `school_district` | object or null | The unified school district, or else the elementary one: `geoid` and `name`. |
| `credits_used` | integer | Credits debited for this call: 1 when `status` is `matched` with a live key, else `0`. |
| `cached` | boolean | `true` when the answer came from the 30-day cache. |

```json title="Response"
{
  "id": "lkp_01M8CEFKXRYJS1HJSEGWVBDAVK",
  "object": "census_tract",
  "input": "1600 Pennsylvania Ave NW, Washington, DC 20500",
  "status": "matched",
  "matched_address": "1600 PENNSYLVANIA AVE NW, WASHINGTON, DC, 20500",
  "coordinates": { "latitude": 38.898702605245, "longitude": -77.035189204737 },
  "tiger_line": { "id": "76225813", "side": "L" },
  "state": { "fips": "11", "code": "DC", "name": "District of Columbia" },
  "county": { "geoid": "11001", "name": "District of Columbia" },
  "county_subdivision": { "geoid": "1100150000", "name": "Washington city" },
  "place": { "geoid": "1150000", "name": "Washington city" },
  "tract": { "geoid": "11001980000", "code": "980000", "name": "Census Tract 9800" },
  "block_group": { "geoid": "110019800001", "code": "1" },
  "block": { "geoid": "110019800001034", "code": "1034" },
  "congressional_district": { "geoid": "1198", "code": "98", "name": "Delegate District (at Large)", "congress": 120 },
  "state_legislative_upper": { "geoid": "11002", "name": "Ward 2" },
  "state_legislative_lower": null,
  "metro_area": { "geoid": "47900", "name": "Washington-Arlington-Alexandria, DC-VA-MD-WV Metro Area" },
  "zcta": "20006",
  "school_district": { "geoid": "1100030", "name": "District of Columbia Public Schools" },
  "credits_used": 1,
  "cached": false
}
```

The ZCTA of this address, `20006`, differs from its ZIP code, `20500`: a ZIP code reserved for one organization, like this one, often has no tabulation area of its own, so the address falls in the one around it.

## Act on the status

| `status` | What it means | What to do | Billed |
|---|---|---|---|
| `matched` | The address was found in the Census address ranges. | Compare `matched_address` with the address you sent, then use the coordinates and geographies. A different city or street means another address matched. | Yes, and cached 30 days |
| `no_match` | The Census Geocoder found no address range for it. | Check the house number, street and ZIP code. PO boxes, rural routes and new streets often cannot match. | No |

Answers other than `matched` are never cached, so the next request asks the Census Geocoder again.

## How the lookup works

1. Runs of spaces in the address are collapsed, and the address goes to the `onelineaddress` geographies service of the Census Geocoder, with the current address ranges (benchmark `Public_AR_Current`), the current geographies (vintage `Current_Current`) and every layer.
2. The Census Geocoder finds the TIGER/Line street segment whose address range holds the house number and interpolates the point along it, on the side of the street of that number. The point is on the street in front of the address, not on the building.
3. Only the first match is kept. Each geography is read from its layer: the 2020 Census blocks, the block group (or the first 12 digits of the block GEOID when the layer is missing), the tract, county, county subdivision and state, the congressional district of the current Congress, the state legislative districts, the incorporated or census designated place, the metropolitan or micropolitan area, the unified or elementary school district, and the ZCTA.
4. When the Census Geocoder finds no match, or answers that it cannot read the address, the status is `no_match`.

The result is cached by address, in upper case with spaces and commas normalized, so `1600 pennsylvania ave nw,washington, dc 20500` reads the same cached result.

## Examples

### Geocode an address with a test key

Test keys return a sample address in Springfield, Illinois, without calling the Census Geocoder: an address that contains `nowhere` returns `no_match`, and any other address returns the sample below. With a test key in `QELKA_API_KEY`, this request returns:

```bash title="cURL"
curl https://api.qelka.com/v1/census/tract \
  --max-time 30 \
  -H "Authorization: Bearer $QELKA_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"address": "1 Test Way, Springfield, IL 62701"}'
```
```javascript title="Node.js"
const response = await fetch('https://api.qelka.com/v1/census/tract', {
  method: 'POST',
  headers: {
    Authorization: `Bearer ${process.env.QELKA_API_KEY}`,
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({ address: '1 Test Way, Springfield, IL 62701' }),
  signal: AbortSignal.timeout(30_000),
})
const result = await response.json()
console.log(result)
```
```python title="Python"
import os

import requests

api_key = os.environ["QELKA_API_KEY"]
response = requests.post(
    "https://api.qelka.com/v1/census/tract",
    headers={"Authorization": f"Bearer {api_key}"},
    json={"address": "1 Test Way, Springfield, IL 62701"},
    timeout=30,
)
result = response.json()
print(result)
```

```json title="Response"
{
  "id": "lkp_01M8CG3A9VHZ2N6QX4T7DRKW8B",
  "object": "census_tract",
  "input": "1 Test Way, Springfield, IL 62701",
  "status": "matched",
  "matched_address": "1 TEST WAY, SPRINGFIELD, IL, 62701",
  "coordinates": { "latitude": 39.8, "longitude": -89.65 },
  "tiger_line": { "id": "000000001", "side": "L" },
  "state": { "fips": "17", "code": "IL", "name": "Illinois" },
  "county": { "geoid": "17167", "name": "Sangamon County" },
  "county_subdivision": null,
  "place": null,
  "tract": { "geoid": "17167000100", "code": "000100", "name": "Census Tract 1" },
  "block_group": { "geoid": "171670001001", "code": "1" },
  "block": { "geoid": "171670001001000", "code": "1000" },
  "congressional_district": { "geoid": "1713", "code": "13", "name": "Congressional District 13", "congress": 120 },
  "state_legislative_upper": null,
  "state_legislative_lower": null,
  "metro_area": null,
  "zcta": null,
  "school_district": null,
  "credits_used": 0,
  "cached": false
}
```

## Errors

| Status | Type | When |
|---|---|---|
| 400 | [invalid_request](https://qelka.com/docs/errors#invalid_request) | `address` is missing, shorter than 5 or longer than 300 characters, the body is not a JSON object, or it has a field the request table does not list |
| 401 | [invalid_api_key](https://qelka.com/docs/errors#invalid_api_key) | The key is missing, unknown or revoked |
| 402 | [insufficient_credits](https://qelka.com/docs/errors#insufficient_credits) | Your balance is less than 1 credit (live keys only) |
| 403 | [forbidden](https://qelka.com/docs/errors#forbidden) | The key is restricted to other endpoints |
| 405 | [invalid_request](https://qelka.com/docs/errors#invalid_request) | The method is not `POST` |
| 429 | [rate_limited](https://qelka.com/docs/errors#rate_limited) | Too many requests: wait `Retry-After` seconds |
| 500 | [internal_error](https://qelka.com/docs/errors#internal_error) | Unexpected error on our side: retry with backoff |
| 502 | [upstream_unavailable](https://qelka.com/docs/errors#upstream_unavailable) | The Census Geocoder could not be reached, answered with an error or did not answer in time: retry later |

No error is billed. An address that does not match is not an error: it is a `200` with `status: "no_match"` and `credits_used: 0`.

## Related

- [Census tract lookup API](https://qelka.com/products/census-tract-lookup)
- Free tools: [census tract finder](https://qelka.com/tools/census-tract-finder), [address to coordinates](https://qelka.com/tools/address-to-coordinates)
- [Batch](https://qelka.com/docs/api-reference/batch): up to 100 addresses in one call, each item with `type: "census_tract"`
- [Bulk](https://qelka.com/docs/api-reference/bulk): a whole column of addresses with `type=census_tract`
- [Caching](https://qelka.com/docs/caching), [Errors](https://qelka.com/docs/errors), [Test mode](https://qelka.com/docs/test-mode)
