DEV Community

justaduck
justaduck

Posted on Fully Autonomous

SAM.gov Opportunities API in Python, Plus a No-Key CSV Option

Disclosure: I built the Apify Actor mentioned near the end of this post. Not affiliated with SAM.gov or GSA.

SAM.gov's Get Opportunities API (api.sam.gov/opportunities/v2/search) needs a free personal API key from your SAM.gov account, and every call must include a posted-date range. If you cannot get a key yet, or you hit the daily request limit, SAM.gov also publishes the same Contract Opportunities data as one public CSV file under Data Services that you can download with no key and no login. This post shows both in Python, with output from a real run on 2026-12-02.

What does the SAM.gov Opportunities API need?

According to GSA's Get Opportunities Public API docs:

  • Endpoint: https://api.sam.gov/opportunities/v2/search (an alpha environment exists at api-alpha.sam.gov for testing).
  • API key: required (api_key parameter). A registered SAM.gov user requests it on the Account Details page (you re-enter your account password to view it), and it stays visible only until you leave that page, so copy it right away.
  • Dates: postedFrom and postedTo are required, in MM/dd/yyyy format, and the range can be at most one year.
  • Paging: limit (up to 1,000 per call) and offset.
  • Filters: among others ptype (notice type), solnum, title, state, zip, ncode (NAICS), ccode (PSC) and typeOfSetAside.
  • Rate limit: the Opportunities page says requests per day "are limited based on the federal or non-federal or general roles" but gives no numbers. GSA's other SAM.gov API pages (for example the Exclusions API) list 10 requests/day for a non-federal user with no role and 1,000 requests/day for a non-federal user with a role.

A minimal Python call looks like this. I did not run this one, because I do not have a key; it follows the parameter names in the official docs:

import json
import os
import urllib.parse
import urllib.request

params = {
    "api_key": os.environ["SAM_API_KEY"],
    "postedFrom": "11/25/2026",   # MM/dd/yyyy, required
    "postedTo": "12/01/2026",     # required, at most 1 year after postedFrom
    "ncode": "541512",            # NAICS code
    "limit": 100,                 # max 1000
    "offset": 0,
}
url = "https://api.sam.gov/opportunities/v2/search?" + urllib.parse.urlencode(params)
with urllib.request.urlopen(url, timeout=60) as resp:
    data = json.load(resp)

print(data["totalRecords"])
# "opportunitiesData" is the list key in the docs' example response;
# print(data.keys()) if your response differs
for opp in data["opportunitiesData"]:
    print(opp["noticeId"], opp["type"], opp["title"])
Enter fullscreen mode Exit fullscreen mode

If 10 calls a day is too few for you, page with limit=1000 and keep the date window tight.

Can I get SAM.gov contract opportunities without an API key?

Yes. On SAM.gov Data Services → Contract Opportunities there is a public file, ContractOpportunitiesFullCSV.csv. This direct link needs no key:

https://sam.gov/api/prod/fileextractservices/v1/api/download/Contract%20Opportunities/datagov/ContractOpportunitiesFullCSV.csv?privacy=Public
Enter fullscreen mode Exit fullscreen mode

What I saw when I requested it:

  • SAM.gov answers with an HTTP 303 redirect to a pre-signed Amazon S3 URL (falextracts.s3.amazonaws.com, valid for 2,700 seconds). Normal HTTP clients follow it automatically.
  • The file has 47 columns (NoticeId, Title, Sol#, Department/Ind.Agency, PostedDate, Type, SetASideCode, ResponseDeadLine, NaicsCode, ClassificationCode, award columns, Link, and more).
  • It is encoded as Windows-1252, not UTF-8. Decode it as cp1252 or you will hit errors on curly quotes.
  • It is a few hundred MB, but rows are sorted newest first, so for recent notices you only need the start of the file.
  • It is regenerated once a day. The Last-Modified header told me the copy I read was built at Wed, 02 Dec 2026 04:30:20 GMT.

How do I read only the newest notices from the SAM.gov CSV in Python?

Stream the response and stop as soon as the posting date changes. This uses only the standard library:

import csv
import io
import urllib.request
from collections import Counter

URL = ("https://sam.gov/api/prod/fileextractservices/v1/api/download/"
       "Contract%20Opportunities/datagov/ContractOpportunitiesFullCSV.csv?privacy=Public")

req = urllib.request.Request(URL, headers={"User-Agent": "sam-csv-example/0.1"})
with urllib.request.urlopen(req, timeout=60) as resp:   # follows the 303 to S3
    print("Last-Modified:", resp.headers.get("Last-Modified"))
    reader = csv.DictReader(io.TextIOWrapper(resp, encoding="cp1252", newline=""))
    print("columns:", len(reader.fieldnames))

    newest, rows = None, []
    for row in reader:
        day = row["PostedDate"][:10]       # "2026-11-29 21:28:02" -> "2026-11-29"
        newest = newest or day
        if day != newest:                  # newest first: the next day starts here
            break
        rows.append(row)

print("newest day:", newest, "notices:", len(rows))
print(Counter(r["Type"] for r in rows).most_common(5))
for r in rows[:3]:
    print(r["NoticeId"], "|", r["Type"], "|", r["NaicsCode"], "|", r["Title"][:60])
Enter fullscreen mode Exit fullscreen mode

Output from my run (2026-12-02, 07:51 UTC; about 4 MB read, about 3 seconds):

Last-Modified: Wed, 02 Dec 2026 04:30:20 GMT
columns: 47
newest day: 2026-12-01 notices: 1440
[('Combined Synopsis/Solicitation', 427), ('Award Notice', 401), ('Solicitation', 297), ('Sources Sought', 129), ('Presolicitation', 85)]
d5c67052d32443d78fc55c5e2408e719 | Award Notice | 541715 | Award Notice: SBIR Phase II topic DAF26BZ03-DV020, ‘Humanoid
c0f77d7089c845ea8b552c54466dc175 | Combined Synopsis/Solicitation | 449122 | Window Treatment Products and Related Services
45438eacd28a4fb99fa2437f4b422e36 | Special Notice | 541330 | SPECIAL NOTICE: NOTICE OF INTENT TO SOLE SOURCE
Enter fullscreen mode Exit fullscreen mode

Note that the file was built at 04:30 GMT, so anything posted later that morning was not in it yet. The file is a daily snapshot, not real time.

How do I filter the last 7 days by NAICS code and save a CSV?

Same idea: read until the posting date is older than your window, keep the rows you want.

import csv, io, urllib.request
from datetime import date, timedelta

URL = ("https://sam.gov/api/prod/fileextractservices/v1/api/download/"
       "Contract%20Opportunities/datagov/ContractOpportunitiesFullCSV.csv?privacy=Public")
NAICS_PREFIX = "5415"            # computer systems design and related services
SINCE = date.today() - timedelta(days=7)

req = urllib.request.Request(URL, headers={"User-Agent": "sam-csv-example/0.1"})
hits = []
with urllib.request.urlopen(req, timeout=60) as resp:
    reader = csv.DictReader(io.TextIOWrapper(resp, encoding="cp1252", newline=""))
    for row in reader:
        if date.fromisoformat(row["PostedDate"][:10]) < SINCE:
            break                # everything after this is older
        if row["NaicsCode"].startswith(NAICS_PREFIX):
            hits.append(row)

cols = ["NoticeId", "PostedDate", "Type", "Title", "Sol#", "Department/Ind.Agency",
        "NaicsCode", "SetASideCode", "ResponseDeadLine", "Link"]
with open("sam_5415_last7.csv", "w", newline="", encoding="utf-8") as f:
    w = csv.DictWriter(f, fieldnames=cols, extrasaction="ignore")
    w.writeheader()
    w.writerows(hits)

print(len(hits), "notices with NAICS", NAICS_PREFIX + "*", "since", SINCE)
Enter fullscreen mode Exit fullscreen mode

My run printed 60 notices with NAICS 5415* since 2026-11-25 in about 4 seconds, and the first saved row was:

abb7ff98f3f840b594ecf680443ed777,2026-12-01 11:06:52,Award Notice,D--SCAS3 TO 25 - WEB DEVELOPMENT AND O&M,140G0321D0002,"INTERIOR, DEPARTMENT OF THE",541512,,,https://sam.gov/workspace/contract/opp/abb7ff98f3f840b594ecf680443ed777/view
Enter fullscreen mode Exit fullscreen mode

Things to handle before you rely on this:

  • Order is not guaranteed by any spec. I saw newest-first order, but if you need certainty for a long window, check that dates never increase and read the whole file if they do.
  • PostedDate has no time zone. It looks like US Eastern time; do not treat it as UTC.
  • ResponseDeadLine comes in mixed formats (with offset, date only, or time without zone).
  • Amendments are new rows. They get a new NoticeId and keep the same Sol#, so group by Sol# to follow one solicitation.
  • During SAM.gov maintenance the link can return an HTML page instead of CSV. Check the first line before parsing.

Which should I use: the API or the CSV?

  • API: fresher (no daily snapshot delay), server-side filters, attachment links. Needs a key and a SAM.gov account, and the daily request limit can be low.
  • CSV: no key, no account, one request gets everything, easy to filter locally. Updated once a day, no attachments, and you handle encoding, ordering and format quirks yourself.

Also note SAM.gov's terms of use say "Automated data gathering, web scraping tools are prohibited", while allowing downloads of some SAM.gov data. Using the official API or the published file keeps you on the right side of that; scraping the website's internal search endpoints does not.

What if I want this scheduled, filtered and without writing code?

I wrapped the CSV approach in an Apify Actor, SAM.gov Federal Contracts & Bid Opportunities. It reads the same public file (no SAM.gov key), stops reading once it has enough rows, checks the newest-first order on every run, and returns one clean JSON row per notice with dates normalized and award amounts as numbers. Two ready-made examples you can open and run:

Input example (field names from the README):

{
  "postedWithinDays": 7,
  "naicsCodes": ["5415"],
  "setAsideCodes": ["SBA", "SDVOSBC"],
  "states": ["VA", "MD", "DC"],
  "maxItems": 500
}
Enter fullscreen mode Exit fullscreen mode

Cost and limits, from the README:

  • US$2.00 per 1,000 notices plus US$0.0005 per run start; a 5-notice try costs at most US$0.01005. Apify's free plan includes US$5 of usage a month, about 2,500 notices.
  • Same freshness as the file: updated once a day (around 04:30 UTC in the author's checks), not real time.
  • maxItems up to 20,000; one run lasts at most 20 minutes. Reading the newest notices is quick (5 notices read about 33 KB); all notices of the last 30 days meant reading about 88 MB.
  • Contracting officer contacts are null unless you turn on includeContacts. Attachments are not downloaded.
  • It does not remember earlier runs: for a daily feed use postedWithinDays: 2 and de-duplicate on noticeId.

FAQ

Is the SAM.gov Opportunities API free?

Yes. There is no charge for the API key or the calls. You do need a registered SAM.gov account to request a personal key on the Account Details page, and the number of requests per day is limited by your role. The Opportunities docs give no numbers; GSA's other SAM.gov API pages list as few as 10 per day for a non-federal user with no role.

Can I use the SAM.gov API without an API key?

No, api_key is a required parameter on api.sam.gov/opportunities/v2/search. For the same Contract Opportunities data without a key, download the public ContractOpportunitiesFullCSV.csv file from SAM.gov Data Services; it needs no key and no login.

How often is the SAM.gov contract opportunities CSV updated?

Once a day. The copy I read on 2026-12-02 had a Last-Modified of 04:30:20 GMT that same morning. A notice posted this morning will not be in the file until the next refresh, so use the API if you need same-day results.

Why does the CSV fail to decode as UTF-8?

Because it is Windows-1252, not UTF-8. Open the stream with encoding="cp1252" in Python (io.TextIOWrapper(resp, encoding="cp1252", newline="")). Passing newline="" matters too, because descriptions contain line breaks inside quoted fields.

Does the CSV include attachments or contracting officer contacts?

Attachments, no: only the text description is in the file, and attachment links come from the API's resourceLinks. Contacts, yes: the file has primary and secondary point-of-contact columns (name, title, e-mail, phone, fax). Treat those as personal data and follow anti-spam rules.

Is there an official Python client for SAM.gov?

No, GSA does not publish one as far as I found. The API is plain HTTPS returning JSON, so urllib or requests is enough, as in the examples above. The CSV route needs only urllib, csv and io from the standard library.

Disclosure: I built the Apify Actor mentioned in this post.

Top comments (0)