Skip to content

Forum in maintenance, we will back soon 🙂

Notifications
Clear all

API Template

81 Posts
3 Users
15 Reactions
247 Views
DariDar
(@dari-dar)
Posts: 47
Trusted Member Customer Registered
Topic starter
 

Hello Hassan,

I just finished the build and sell apis course. At the end you have a template. Can you give please more explenation? Here my questions:

- is this template the place where i can create my apis local at my computer (with FastApi)?

- after i created my apis with the help of this template, wich part of the codes i have to upload to rapidapi?

- should all the codes of this template be put online in rapidapi to make it work? If i understand it right, some of the codes in your template are there for security reasons. The "publish to rapidapi" video unfortunately is very short and doesnt explain this details.

 
Posted : 01/26/2024 3:08 pm
Topic Tags
Hasan Aboul Hasan
(@admin)
Posts: 1276
Member Admin
 

Hi @dari-dar

Yeah, this is a template where you can add your endpoints, and then publish online, it will help you get started fast.

You will upload the full code; it all works together.

you don't publish on RapidAPI; You publish on a hosting service like DigitalOcean, Heurko, and others.

Then you just configure and connect with RapidAPI. 

did you build your own API and publish it online? dont worry, if you are facing problems on RapidAPI, we will help. we are here everyday

 
Posted : 01/27/2024 10:25 am
DariDar
(@dari-dar)
Posts: 47
Trusted Member Customer Registered
Topic starter
 

Thank you for your answer Hassan! Sorry I have a few more questions.

Now I understood, that I first have to push the full template on Github then from there to a hoster like Digital Ocean. when the api is on the hoster online I can use this my own api for my own projects, but if then I publish my hosted code from Digital Ocean to RapidApi is to make it accessible to others so that I can earn money with it?

Did I understand it right, that every tool I build is reccomandable to integrate it in your template when I upload to the hoster so to have all security and best practice? What is mongo in the template?

I also had the Saas course, so If i upload to hoster I can then use my online python code for my Saas for example in WordPress?

If I use Streamlit, I also have first to upload all python code to a hoster or in streamlit all code gets upload to streamlit so i dont need a hoster?

In streamlit every tool has to be upload for its own or can i make accessible many different tools on streamlit from only one user-interface?

Thank you already for your time and your help! Very appreciated!

 
Posted : 01/27/2024 8:48 pm
Hasan Aboul Hasan
(@admin)
Posts: 1276
Member Admin
 

@dari-dar Yeah, API > Github > Hosting > RapidAPI

yes, the template is ready for you; you need to add your own endpoints. 

Mongo is a database system, it is not mandatory, but in case someone wants to use it, then is is also built in the template

yes, exactly, this will be the python backend for your tools, this is what I do.

if you use streamlit, yes they provide a free hosting, but for hosting streamlit apps and not APIs.

 

 

 
Posted : 01/28/2024 9:35 am
DariDar reacted
DariDar
(@dari-dar)
Posts: 47
Trusted Member Customer Registered
Topic starter
 

Thank you sir!

 
Posted : 01/28/2024 7:02 pm
DariDar
(@dari-dar)
Posts: 47
Trusted Member Customer Registered
Topic starter
 

Hello Hassan,

I tryed to use your fast-api-template but i get errors from the beginning: When running with debug i get this:
INFO: Will watch for changes in these directories: ['C:\\Users\\dar\\Python-Fast-API-Template-main-CIG']
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO: Started reloader process [15184] using StatReload
ERROR: Error loading ASGI app. Could not import module "main".

when i open the link in chrome browser i get this:
The website cannot be reached127.0.0.1 has refused the connection.
Try the following:
Check connection
Check proxy and firewall
ERR_CONNECTION_REFUSED

 

I use windows for my python codes, but then i also have problems when i try to load python code on a mac.

I saw in other tutorials that they install something like jupiter notebook. Would this help to make my codes run also on other places like mac computer?

 
Posted : 02/03/2024 10:03 am
Hasan Aboul Hasan
(@admin)
Posts: 1276
Member Admin
 

@dari-dar can you please sens a screenshot on how you are running it

 
Posted : 02/03/2024 10:34 am
DariDar
(@dari-dar)
Posts: 47
Trusted Member Customer Registered
Topic starter
 

From the beginning I had this error.

I tried to follow chatgpt in debugging and I had make vanish all errors. according to chatgpt also some code in the template is deprected - this was the case with the @app.on_event("startup") code. chatgpt said to change it to lifespan. I did how you can see in second screenshot. At the end all was functioning but the code had problem with the config.json file.

Alltought it is in the right folder, it could not be found whatever i tried - see screenshot 3.

Now I turned back to your template-code without changes. I just watched again your video, and compared the downloaded code with yours in the video. I see that in the downloaded template there is not the log folder and I see that you created a virtual enviroment (venv) in your code in the app folder. So it is necessary to create venv to make it run correctly?

here my last screenshot from the comparision:

 
Posted : 02/03/2024 5:44 pm
SSAdvisor
(@ssadvisor)
Posts: 1139
Noble Member
 

@dari-dar can you please share your main.py file? Use the code icon (<>) above to paste in the code. Your execution shows that the process cannot find the main.py file.

Regards,
Earnie Boyd, CEO
Seasoned Solutions Advisor LLC
Schedule 1-on-1 help
Join me on Slack

 
Posted : 02/03/2024 6:13 pm
DariDar
(@dari-dar)
Posts: 47
Trusted Member Customer Registered
Topic starter
 

This is the main.py - without any changes from the downloaded template:

<

# optimized
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
from fastapi.responses import RedirectResponse
from aiohttp import ClientSession
from fastapi.middleware.cors import CORSMiddleware
from fastapi.security import APIKeyHeader
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.exceptions import HTTPException as StarletteHTTPException

import openai
from starlette.applications import Starlette
from slowapi import Limiter, _rate_limit_exceeded_handler
from slowapi.util import get_remote_address
from slowapi.middleware import SlowAPIMiddleware
from slowapi.errors import RateLimitExceeded
from starlette.requests import Request
from starlette.types import ASGIApp

from .routers import tools
from .helpers import record_log, LogLevel,get_calling_function_name ,get_calling_module_name

# Assumed imports from your other modules
from .routers import (
    tools
)
from .mongo import establish_connection, mongo_db_instance
from .logger_setup import initialize_logger
from .config_loader import config
API_KEY_NAME = config["API_KEY_HEADER_NAME"]
API_KEY = config["API_KEY_PASSPHRASE"]
api_key_header = APIKeyHeader(name=API_KEY_NAME, auto_error=True)

WHITELISTED_PATHS = ["/customdocs", "/openapi.json", "/"]

app = FastAPI(
    title="API System",
    description="Private APIs For YourName",
    version="1.0.0",
    servers=[
        {"url": "https://api.url/", "description": "Production server"},
        {"url": "http://127.0.0.1:8000", "description": "Development server"}
    ],
    docs_url="/customdocs"
)

#app = FastAPI(docs_url="/customdocs")
limiter = Limiter(key_func=get_remote_address, default_limits=["1000/minute"])
app.state.limiter = limiter
app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)
app.add_middleware(SlowAPIMiddleware)

# Logger setup at top level
logger = initialize_logger()
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)
# Middleware for Logging with enhanced context
class LogMiddleware(BaseHTTPMiddleware):
    async def dispatch(self, request: Request, call_next):
        try:
            response = await call_next(request)
        except Exception as exc:
            logger.error(f"Unhandled error in request {request.url.path}: {exc}", exc_info=True)
            raise exc
        logger.info(f"Request {request.method} {request.url.path}, Response: {response.status_code}")
        return response

app.add_middleware(LogMiddleware)

class APIKeyMiddleware(BaseHTTPMiddleware):
    async def dispatch(self, request: Request, call_next):
        if request.url.path not in WHITELISTED_PATHS:
            api_key = request.headers.get(API_KEY_NAME)
            if api_key != API_KEY:
                return JSONResponse(
                    status_code=401, content={"detail": "Invalid API key"}
                )
        return await call_next(request)
   
app.add_middleware(APIKeyMiddleware)

original_openapi = app.openapi
def custom_openapi():
    if app.openapi_schema:
        return app.openapi_schema
    openapi_schema = original_openapi()
    openapi_schema["components"]["securitySchemes"] = {
        API_KEY_NAME: {"type": "apiKey", "in": "header", "name": API_KEY_NAME}
    }
    openapi_schema["security"] = [{API_KEY_NAME: []}]
    app.openapi_schema = openapi_schema
    return app.openapi_schema
app.openapi = custom_openapi
@app.on_event("startup")
async def startup():
    try:
        print("establishing connection to MongoDB")
        #await establish_connection()
    except Exception as ex:
        record_log(ex,get_calling_module_name(),get_calling_function_name(), LogLevel.ERROR)
        #logger.error(f"Error occurred on startup_mongoObj.connect(): {e}", exc_info=True)
       
@app.on_event("shutdown")
async def shutdown():
    try:
        print("close connection to MongoDB")
        #await mongo_db_instance.close()
    except Exception as e:
        logger.warning(f"error occurred on shutdown_MongoDB.close(): {e}", exc_info=True)

@app.get("/health")
async def read_health():
    try:
        # Assuming mongoObj has a method to check connection health
        #if not await mongo_db_instance.is_connected():
            #raise Exception("MongoDB is disconnected")
       
        # Additional checks can go here
        return {"status": "healthy"}

    except Exception as ex:
        # Log the specific error for internal reference
        record_log(ex,get_calling_module_name(),get_calling_function_name(), LogLevel.ERROR)
        # Return an appropriate error status code
        return JSONResponse(
            status_code=503,
            content={"status": "unhealthy", "details": str(ex)}
        )
@app.exception_handler(StarletteHTTPException)
async def http_exception_handler(request: Request, exc: StarletteHTTPException):
    try:

        logger.error(
            f"An HTTP error occurred: {exc.detail}",
            extra={"request_path": request.url.path}
        )
        return JSONResponse(
            status_code=exc.status_code,
            content={"message": exc.detail},
        )
    except:
        return
        #nothing

@app.exception_handler(Exception)
async def global_exception_handler(request: Request, exc: Exception):
    try:
        logger.error(
            f"An unexpected error occurred while processing path {request.url.path}: {exc}",
            exc_info=True,
        )
        return JSONResponse(
            status_code=500,
            content={
                "success": False,
                "message": "An unexpected error occurred",
                "result": None,
            },
        )
    except:
        return
        #nothing
app.include_router(tools.router, tags=["tools"])

>

 
Posted : 02/03/2024 7:10 pm
SSAdvisor
(@ssadvisor)
Posts: 1139
Noble Member
 

@dari-dar you have imported Request from two different modules; one from FastAPI and one from Starlette, you should either remove one or alias one of them if you need both. Also, make sure you have uvicorn logs enabled and check them after execution.

Regards,
Earnie Boyd, CEO
Seasoned Solutions Advisor LLC
Schedule 1-on-1 help
Join me on Slack

 
Posted : 02/04/2024 5:33 am
DariDar
(@dari-dar)
Posts: 47
Trusted Member Customer Registered
Topic starter
 

But this is 1:1 from Hassans Template. So something is wrong in the provided template?

I don't know how to enable uvicorn logs and check after execution. Would be nice if there is a little bit more explenation in the video-lesson.

 
Posted : 02/04/2024 9:37 am
SSAdvisor
(@ssadvisor)
Posts: 1139
Noble Member
 

@dari-dar Mr @Hasan will have to respond to the template code. As for logging in uvicorn check this.

Regards,
Earnie Boyd, CEO
Seasoned Solutions Advisor LLC
Schedule 1-on-1 help
Join me on Slack

 
Posted : 02/04/2024 3:40 pm
DariDar
(@dari-dar)
Posts: 47
Trusted Member Customer Registered
Topic starter
 

Thank you @ssadvisor! I was able to run the template now. But I had to put the main.py in the main folder instead of app folder. Adjusted also all the imports from .modules to app.modules...  Don't know if this is the bes practice but now it functions.

@admin is it ok to put the main.py out of the app folder or is this not best practice?

 
Posted : 02/04/2024 5:53 pm
SSAdvisor reacted
DariDar
(@dari-dar)
Posts: 47
Trusted Member Customer Registered
Topic starter
 

Hello @admin Hassan,

I am just reviewing all what I have learned and I have to tell, that I find it all very confusing. Can you please make a video where you explain the whole workflow from having a ready app like the plagiarism-checker or something else that also runs with openai and then implement it in your template and after that upload on github, from there upload to a hoster and maybe from there upload ro rapidapi?

I have also the saas-course and I have created a website and now I want to use one of my apis integrated in your template to use in my saas. but how to integrate my python code with all files and folders in your template i still don't understand. Do i have to integrate the files in the app folder or in any other folder? Have to adjust some code in the main.py? If you could please show more in detail explained slowly and simply step by step?

Best regards

Dari

 
Posted : 02/04/2024 6:48 pm
Page 1 / 6
Share:
[the_ad_group id="312"]