Reputation: 1
First off, I'm a beginner at working with APIs so apologies if the answer is obvious or if I'm asking for the wrong information. I'm attempting to call an API that will return travel per diem rates based on ZIP and fiscal year. The endpoint is "https://api.gsa.gov/travel/perdiem/v2/rates/zip/{zip}/year/{year}". From what I understand, the {zip} and {year} represent path parameters that will be replaced with the actual ZIP and year when the request is sent? Here is what I have (deleted the key for this post).
import requests
api_url = "https://api.gsa.gov/travel/perdiem/v2/rates/zip/{zip}/year/{year}"
api_key = "xxx"
headers = {
"X-API-KEY": api_key,
}
payload = {
"zip": 22041,
"year": "2022"
}
r = requests.post(api_url, headers=headers, params=payload)
print(r.json())
When I go into the actual url and change {zip} and {year} to the actual values, it works. However, I cannot figure out how to pass the values in as parameters. When I run it now, it returns empty:
{'request': None, 'errors': None, 'rates': [], 'version': None}
. So I'm pretty sure I just don't know how to pass in the parameters to the url properly.
The documentation provided is just an OpenAPI text file and I've included the info regarding this endpoint below:
openapi: 3.0.0
info:
title: "GSA Perdiem API"
description: >-
Per Diem Rates are the allowed reimbursement rates for hotel stays and meals for federal travelers. Rates are set for each of the federal government's fiscal years (October 1st to September 30th) GSA is responsible for setting the rates in the continental United States. Many businesses and other organizations adopt these rates as well. This API provides access to the current rate information.
version: 2.0.0
path:
/v2/rates/zip/{zip}/year/{year}:
get:
summary: "Get perdiem rates by ZipCode and year"
parameters:
- name: "zip"
in: "path"
description: "The ZipCode to filter by"
required: true
schema:
type: integer
format: integer
- name: "year"
in: "path"
description: "The fical-year to filter by"
required: true
schema:
type: string
format: string
responses:
200:
description: "Successful. Data will be returned in JSON format."
400:
description: "Bad request. Verify the query string parameters that were provided."
403:
description: "API key is not correct or was not provided."
servers:
- url: 'https://api.gsa.gov/travel/perdiem'
components:
securitySchemes:
ApiKeyAuth: # arbitrary name for the security scheme
type: apiKey
in: header # can be "header", "query" or "cookie"
name: X-API-KEY # name of the header, query parameter or cookie
security:
- ApiKeyAuth: []
Any help is appreciated!
Upvotes: 0
Views: 2218
Reputation: 2595
The proper context for formatting a string like this in Python3+ is
url = f"https://api.gsa.gov/travel/perdiem/v2/rates/zip/{zipvar}/year/{yearvar}"
The f
defining it as a formatted string
You also should not use zip
as the name of a variable, since it is the name of a built-in function.
Upvotes: 0