How to make an API such that it could take string & int parameter in request URL of API to pull out specific data from API in Python

API (Application Programming Interface) helps to communicate date between two sides.

We are making a API , which could take string & int parameter in it’s Request URL on user side to pull out the required data.

Here , we are making two files one file is for API & second to transfer string & int parameter in URL.

We are using Flask framework & REST API , make sure Flask , REST are installed on your machine.

API Format

from flask import Flask
from flask_restful import Api, Resource

app=Flask(__name__)
api =Api(app)

class HelloWorld(Resource):
    def get(self):
        return {"data":"hello world"}   #JSON Format

api.add_resource(HelloWorld,"/helloworld")

if __name__ == "__main__":
    app.run(debug=True)

As you could see in above code , We have made a API using python.

Request file Format

import requests
BASE = "http://127.0.0.1:5000/"
response=requests.get(BASE + "helloworld")
print(response.json())

We are going to use this Request file to transfer string & int through URL in API Server.

you will get the below output after running both of above files simultaneously –

{'data': 'hello world'}

So , before giving parameter in URL from request file , we have to do some modification on Server side of API , to accept both the string & int Parameter .

So we are going to include two parameter in API file , so that it could accept the transferred paramater from user side through REQUEST.

API accepting string & int parameter

from flask import Flask
from flask_restful import Api, Resource

app=Flask(__name__)
api =Api(app)

class HelloWorld(Resource):
    def get(self,name,test):
        return {"name":name , "test":test}   #JSON Format

api.add_resource(HelloWorld,"/helloworld/<string:name>/<int:test>")

if __name__ == "__main__":
    app.run(debug=True)

In above code of API , two parameter [ String and int ] is included in 6th , 7th & 8th line.

Passing Parameter from user side Request file

import requests
BASE = "http://127.0.0.1:5000/"
response=requests.get(BASE + "helloworld/psp/25")
print(response.json())

you will get the below output after running both of above files simultaneously –

{'name': 'psp', 'test': 25}

Here , we are passing “psp” as string and “25” as integer to server side , than it goes to API , from where it fetch data linked through this parameter.

As you could see in above API code , same data is linked , so it has gave same data on string and integer.