Fast API - post any key value data - fastapi

I'm using Fast.API
I need an API to allow users to post any data, key/value - I use this to allow users to add custom profile key/value fields to profile, where key is of type string and value is string, number, boolean.
how do I add such route?
I'm using this route, but is not working:
#route.post('/update_profile')
def update_profile(acsess_token, **kargs):
# I need here to get a dictionary like this: { "name": "John", "nick_name": "Juju", "birth_year": 1999, "allow_newsletter": False, }
# and so on.... any key/value pair
pass
I want to be able to post to this route any pair(s) key/value. Is any way to do it with FastAPI?
Thank you.

you can use the request object directly
from fastapi import FastAPI
from fastapi import Request
#app.post("/something")
async def get_body(request: Request):
return await request.json()

After searching for a way to do it, I found this solution:
#route.post('/update_profile')
def update_profile(acsess_token, custom_fields: Optional[dict[str, Any]]):
pass
And this is the best solution so far (for me).

Related

'deserializing' JSON to sqlalchemy model

I'm storing some RESTful api calls into a relational database using sqlalchemy, and I'm looking for a way to 'deserialize' or pythonify some or all of the incoming fields, for instance I might have a json object like
{
'id': 1,
'created_at': '2021-05-27T03:22:38Z',
'count': '3'
}
and I would like a way to "automatically" deserialize the data, similar to how djangorestframework serializers work where fields like "created_at" could be defined as datetime fields, and you could optionally cast 'count' as an integer, and run something like
...setup
# get the json from before as a dict
item = client.get_item()
# somehow serialize here
session = Session()
item_model = Item(**item_data[0])
session.add(item_model)
session.commit()
https://www.django-rest-framework.org/api-guide/serializers/
You have multiple well knowns module to perform serialization (independant of any framework):
Marshmallow: https://marshmallow.readthedocs.io/en/stable/
Typesystem (by the creator of DRF): https://github.com/encode/typesystem
You can also do your own serializer, based on DRF serializer code, if your use case is simple, or just perform a lookup of your dict fields that perform validation/transformation.

how to write an Axios query where I don't know a parent value?

I have a simple firebase DB which looks like
someNode: {
pushId-A: {param1: 'some string'},
pushId-B: {param1: 'some other string')
}
Using Axios GET, is there a way to query someNode for the value of param1 where I don't know the value of the pushId?
I want it to return the pushId of the node that contains "param1: 'some string'.
[EDIT}
I understand now that this is not an Axios question, but rather a Firebase question.
I've read the firebase docs here:
Filtering Data
But when I send the get request with any paramaters other than the auth token, I get back a 400 code. Which tells me it is incorrectly syntaxed.
here is the last part of the DB url
a8/data/houses/-L4OiszP7IOzkfh1f1NY/houseName
where houseName = "Aubergine"
Trying to filter for houseName I am passing:
axios.get('/houses.json/' + '?orderBy="houseName"&startAt="A"' + '&auth=' + token)
I'm keeping the params separate so I can more easily read and change them. Concatenating the strings has no effect.
No matter what combination of params I pass I get the 400 error code. If I leave them off, then the data comes through as expected.
What am I doing wrong????

Redux Form post to /user/:id

I am using redux form, but I would like to post the data from the form to this route user/:id.
But my action just get data from the form, what is the best to way to send this id for action create?
export async function createUser(props){
const request = await post(`/users`, props);
return {
type: CREATE_USER,
payload: request
}
}
How can I pass the id to change my url to /users/${id}
I don't really see anything here related to redux-form, but assuming your id is in your props object, you could do:
const request = await post(`/users/${props.id}`, props);
However, it seems pretty strange that you would even have an id if you are creating the user. Usually the primary key is generated upon creation, so what you have already would be just fine, and your server-side CRUD API should be smarter about not expecting an id.

How to parse a collection's sub-object to find a unique result from many possibilities?

In my user's schema, I have a TokAuth Array with token sub-objects (like multiple mails addresses).
So in a method, when I search the tokens in the current user :
var id = Meteor.userId();
var usercurrent = Meteor.users.findOne({_id: id}, {fields: {"TokAuth": 1}});
var userToken = usercurrent.TokAuth.token;
I got in console.log(userToken)
[ 'fyAyXkXYrQdAlNpjuQfJ8RLU2TpfVGLnptlBs-m1h7xk',
I20170224-20:36:23.202(1)? 'YTwtUbhNTgiEfzFbJq7mESnOoOHeLYxWlqEeJJIG_GiV',
I20170224-20:36:23.206(1)? 'ViA4ydDITJtHDi2c_sArkNtpRYTjFqGL1ju2v00_-rFJ',
I20170224-20:36:23.206(1)? '51ImZcxRADLJr-FPCUL7EFGnTZYjHSZk3XxdqtBV2_fd',
I20170224-20:36:23.207(1)? 'S5aEvqjJ5zTUJqLFCPY1aZ1ZhsQppZTJtYKULM9aS2B3',
I20170224-20:36:23.207(1)? 'mhBs3oxHf2SxZfu2vCZhtiyPfg25fKMY8bKMZD8fx6IG',
I20170224-20:36:23.207(1)? '-rv0FiP-lxoqe8INyCJASV6rZpbgy3euEqB9sO9HsZSV',
I20170224-20:36:23.207(1)? 'zacr6_VBjHTsArov1LmQyZFLwI40fx4J7sygpLosTrli' ]
Beside, I've got a var who is equal to the last token in the userToken sub-object (that's of course expected : not to be the last one, but to be in the sub-object).
console.log (editAuth);
zacr6_VBjHTsArov1LmQyZFLwI40fx4J7sygpLosTrli
So how can I parse userToken to find a match with editAuth? If userToken was just a String, it will be simple but here...
Thanks
Is there a reason you are storing all the tokens as an array as opposed to just updating a single string each time?
That aside, you can check if an array contains a value by using the handy underscore function _.contains
Example:
_.contains( userToken, editAuth ); //returns true or false
In this case, you are simply trying to search for a string within an array of strings. #Sean already provided one solution.
If you are using the meteor ecmascript package then you can just simply use the native Array.includes method.
userToken.includes(editAuth);
On a side note, after using ECMAScript 2015+ for some time now, I find that I can use the native API for almost everything that I used to use underscore or lodash for. Check it out!

Google Cloud Endpoints adding extra parameters

I'm using the 'endpoints-proto-datastore' library and a bit lost in how to add extra parameters to my requests.
Basically I want to add these fields [ID, token] with ID being required. Blossom.io is doing something similar, here Blossom.io Api
Here's my Post method
#Doctor.method(path='doctor', http_method='POST', name='doctor.insert')
def DoctorInsert(self, doctor):
#Edit
Without the Proto-Datastore library:
request = endpoints.ResourceContainer(
message_types.VoidMessage,
id=messages.IntegerField(1,variant=messages.Variant.INT32),
token=messages.IntegerField(2, variant=messages.Variant.INT32)
)
#endpoints.method(request, response,
path='doctor/{id}', http_method='POST',
name='doctor.insert')
How can I do the same using the proto-datastore library?
The way I do it is to add another property to the model decorated with #EndpointsAliasProperty and a setter. I wouldn't call it ID because it may confuse with the App Engine built-in ID.
class Doctor(EndpointsModel):
...
#EndpointsAliasProperty(
setter=set_doctorid, property_type=messages.StringField
)
def doctorid(self):
#Logic to retrieve the ID
return doctorid
def set_doctorid(self, value):
#The ID will be in the value, assign and store it in your model

Resources