In the last post we have seen the importance of having API-Gateway. Today we shall be developing an API Gateway Code to handle the requests and connect with other services. The response of the services will be returned to the applications.
We shall create a project API-Gateway and install below mentioned requirements
fastapi==0.70
PyJWT==1.7.1
uvicorn[standard]==0.15
requests==2.26.0
backoff==1.11.1
hash
Now using a fastapi template like our previous project API-Backend lets build an endpoint /register which will help any applications like web or mobile to call the API-Gateway and sign up an applicant Following will be the code for the end point
@router.post("/register", response_model=RegistrationResponseModel, tags=[router_tag])
def register(registration: CreateRegistrationModel, request: Request):
h1 = HashHandler()
hash_password = h1.hash_password_to_hex_string(registration.password)
applicant = request_handler.post(url=f"{config.API_BACKEND_URL}/applicant/create",
data=json.dumps(
{
"username": registration.username,
"password": hash_password,
"firstname": registration.firstname,
"lastname": registration.lastname
}
),
raise_exception=HTTPException(status_code=status.HTTP_424_FAILED_DEPENDENCY,
detail=f"There was a problem retrieving customer data.")
)
return applicant
As we can see the API-Gateway makes a call to API-Backend at end point /applicant/create/ . Following will be the payload for the API end point
{
"username": registration.username,
"password": hash_password,
"firstname": registration.firstname,
"lastname": registration.lastname
}
The complete code is present in following location
Now lets trigger the end point of API-Gateway and see if it creates an applicant in backend Following is the response of end point. As you see it has HTTP status code 200 which means the call is successful and provides the response of the object created in database
We can check in the backend and see that the object is created as shown below
This program shows us how to build an API-Gateway which manages the incoming traffic and is the only public micro service. Rest of the micro services are publicly exposed