Fastify Server with Random Hex Color Endpoint

  • Share this:

Code introduction


This function creates a Fastify server and defines a GET endpoint to return a random hexadecimal color code.


Technology Stack : Fastify, random, HTTPMethod, HTTPStatus

Code Type : API

Code Difficulty : Intermediate


                
                    
def random_color_hex():
    import random
    from fastify import Fastify
    from fastify import HTTPMethod
    from fastify import HTTPStatus

    app = Fastify()

    @app.get("/random-color", options=True)
    async def get_random_color_color(_request, reply):
        hex_color = f"#{random.randint(0, 0xFFFFFF):06x}"
        reply.status = HTTPStatus.OK
        return {"color": hex_color}

    app.run()