Basic Python/FastAPI

FastAPI

Naranjito 2022. 7. 14. 17:44
  • Step

1. Import FastAPI.
2. Create an app instance.
3. Write a path operation decorator (like @app.get("/")).
4. Write a path operation function.

5. Run the development server.

#bash

% uvicorn main:app --reload

6. Open the browser.

 

Ex 1.

#main.py

from fastapi import FastAPI 

app=FastAPI()

@app.get('/')
async def read_bot():
    return {'hello':'world'}

FastAPI() : an object

app : variable containing instance of FastAPI()
@app : decorator, variable

get : operation

read_bot() : function below the 'decorator'

# http://127.0.0.1:8000/

>>>

{"hello":"world"}

 

Ex 2.

@app.get('/items/')
async def read_item(item_id:str, q:Union[str, None]=None, short:bool=False):
    item={'item_id':item_id}
    if q:
        item.update({'q':q})
    if not short:
        item.update(
            {'description':f'this is {item_id}'}
        )
    return item

 

# http://127.0.0.1:8000/items/?item_id=123&q=100

>>>

{"item_id":"123","q":"100","description":"this is 123"}

The query is the set of key-value pairs that go after the ? in a URL, separated by & characters.

 

Ex 3.

@app.get('/items/{item_id}')
async def read_item(item_id:str, q:Union[str, None]=None, short:bool=False):
    item={'item_id':item_id}
    q = False
    if q:
        print("111")
        item.update({'q':q})
    if not short:
        item.update(
            {'description':f'this is {item_id}'}
        )
    return item
# http://127.0.0.1:8000/items/123?short=True

>>>

{"item_id":"123"}

# http://127.0.0.1:8000/items/123?short=False

>>>

{"item_id":"123","description":"this is 123"}

True=on=1=yes

False=off=0=no

'Basic Python > FastAPI' 카테고리의 다른 글

FastAPI-GET and POST  (0) 2022.07.21
FastAPI-Request Body  (0) 2022.07.20