Slowat_Kela
Slowat_Kela

Reputation: 1511

Python Requests: How to set optional and non-optional parameters at the same time?

I want to query my database with an API.

I have:

import requests
query_params = {'author':'grisham','year':'1998'}
response = requests.get(url='http://111.111.1.1:1000',params=query_params)

This works fine, I can return a data frame of all the books with author grisham published in the year 1998.

However, I want to amend this to say 'author is a compulsory parameter, but the year may optionally be added as a second parameter' (to differentiate for those who just want all his books, versus those who want to know what he published in one particular year).

I can't seem to find in the requests library, instead of params, can i change this to two dictionaries, optional and compulsory params, and pass them in separately? Or is there a better way to do this?

I guess this is sort of what I'm looking for, wondering if there is something more pythonic/efficient/cleaner for my use case?

Upvotes: 2

Views: 2931

Answers (2)

Z4-tier
Z4-tier

Reputation: 7978

Whether a given parameter is required or not, and (if not required) whether you choose to include it in a call to the API makes no difference to the requests library. It's job starts and ends with sending the data you give it and reporting the result. Whether year is required should be included in the API specification. If it is optional, then you can choose to leave it out by simply not including it in the dictionary you send.

Put another way, the year field is a parameter that to the API. It isn't a parameter to the requests library, and requests only knows or cares about it to the extent that it's a piece of data that is needs to send in the body of the request. To requests the year field is always optional, because requests is just passing a message along.

Upvotes: 2

yktoo
yktoo

Reputation: 2986

Like others have said, it's up to you to validate the provided parameters to decide whether any required parameter is correctly passed in. The requests library is only sending it out.

And yes, you can pass two dictionaries into requests.get() (requires Python 3.5+):

query_params = {**required_params, **optional_params}

Upvotes: 2

Related Questions