Home > OS >  Is there a way to ignore an optional query field in an API url?
Is there a way to ignore an optional query field in an API url?

Time:07-24

I'll try to clarify what I mean.

Let's say I have this url:

https://test-api.com/users?age=17&sex=M

There's 2 fields: age and sex. The age field is required but the sex field is optional.

Let's say I want to make a bunch of tests and I use this code:

import requests

def testUserQuery(user_age, user_sex):
    url = f'https://test-api.com/users?age={user_age}&sex={user_sex}'
    response = requests.get(url)

test_query = testUserQuery(17)

Now, assuming that I can't go into the actual code of the API itself and change how empty fields are interpreted...

How can I make this test and leave the user_sex field blank?

In other words, is there a special universal symbol (like "&" which means "and" for every URL in the world) that I can put for user_sex that'll force the API to ignore the field and not cause errors?

Otherwise, I would have to do this:

import requests

def testUserQuery(user_age, user_sex=None):
    if user_sex is None:
       url = f'https://test-api.com/users?age={user_age}'
    elif user_sex is not None:
       url = f'https://test-api.com/users?age={user_age}&sex={user_sex}'
    response = requests.get(url)

test_query = testUserQuery(17)

Imagine if I'm dealing with 10 optional fields. I don't think it would be very efficient to make multiple elif statements to change the URL for every single possible case where an optional field is empty.

I hope I'm being clear, sorry if this sounds confusing.

CodePudding user response:

One way to dynamically achieve this is by changing testUserQuery to accept its arguments as **kwargs then using urllib.parse.urlencode to dynamically build the query string.

from urllib.parse import urlencode


def testUserQuery(base_url='https://test-api.com/users', **kwargs):
    params = urlencode({k: v for k, v in kwargs.items() if v is not None})
    url = f"{base_url}{'?'   params if params else ''}"
    print(url)


testUserQuery()
testUserQuery(a=1)
testUserQuery(a=1, b=2)

This outputs

https://test-api.com/users
https://test-api.com/users?a=1
https://test-api.com/users?a=1&b=2

CodePudding user response:

Here's a simple way to do this by utilising the params parameter:

import requests

URL = 'https://test-api.com/users'

def testUserQuery(**params):
    return requests.get(URL, params=params)

testUserQuery(age=21, sex='male')
testUserQuery(age=21)

In other words, all you have to do is match the parameter names with those that are understood by the API. No need to manipulate the URL

  • Related